0

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.

Robert
  • 7,394
  • 40
  • 45
  • 64
Nemiya
  • 11
  • 1
  • Could be many things: delivery can take a few days if the smtp server keeps trying to deliver, until it finally bounces the email. (You do have a valid sender address that can receive bounces, right?) Your email could end up in a spam folder, or get silently discarded for policy reasons. If your code doesn't break, the question isn't really about programming anymore, though, so imho off-topic here. – Robert Mar 09 '23 at 18:22

1 Answers1

1

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.