Hamza
Hamza

Reputation: 45

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

Upvotes: 1

Views: 387

Answers (1)

Vova
Vova

Reputation: 3541

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())

Upvotes: 1

Related Questions