Python doesn't send email using smtpd, I get no errors but no emails are delivered

101 Views Asked by At

I tried to send an email via Python, but I don't get any mail. I have checked the spam folder but still no results.

My code:

import smtpd

connection = smtpd.SMTP("smtp.gmail.com")
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs=email, msg="Hello")
connection.close()

I get no errors, but no mail is delivered.

1

There are 1 best solutions below

0
Ugyen Norbu On

The smtpd module is deprecated since version 3.6. Thus, I will instead use smtplib.

import smtplib, ssl

# Create secure SSL context
cont = ssl.create_default_context()

server = smtplib.SMTP(smtp_server, port = 587)
server.starttls(context = cont)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
server.quit()

For a cleaner code, sender_email, receiver_email and message should be defined before using the particular line of code.