Search code examples
pythonsmtplib

smtplib No email being sent and no errors appear


I am trying to send a message through smtplib server :

msg = EmailMessage()
msg['Subject'] = 'Product in Stock Alert'
msg['From'] = 'sender'
msg['To'] = 'reciever'
msg.set_content("Hey, {} is now available in stock\n"
                "Check it out soon : {}".format('hamza', 'google.com'))
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login('gmail', 'code')
    smtp.sendmail('sender', 'reciever' ,msg)

i run it through the cmd, but nothing appear or happen, i have lesssecureapps on and 2-step verification off in my gmail account. Thanks in advance


Solution

  • add .as_string() method to msg:

    smtp.sendmail('sender', 'reciever', msg.as_string())
    

    so, code should look like:

    msg = EmailMessage()
    msg['Subject'] = 'Product in Stock Alert'
    msg['From'] = 'sender'
    msg['To'] = 'reciever'
    msg.set_content("Hey, {} is now available in stock\n"
                    "Check it out soon : {}".format('hamza', 'google.com'))
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login('gmail', 'code')
        smtp.sendmail('sender', 'reciever', msg.as_string())