0

I'm trying to send myself an email using Python's smtplib module. Here's the code I'm trying to execute:

import smtplib

sender = 'manas.oid@gmail.com'
receivers = ['manas.oid@gmail.com']

message = """From: From Person <manas.oid@gmail.com>
To: To Person <manas.oid@gmail.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""
try:
   smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except smtplib.SMTPException:
   print "Error: unable to send email"

However, I get a 'Error:unable to send email' message when I try to execute this script. What seems to be wrong with my script?

Manas Chaturvedi
  • 5,210
  • 18
  • 52
  • 104

3 Answers3

2

You did not login and you did not start the connection with smtpObj.starttls().

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
2

To add on to what @Malik says, below are the steps you need to perform before you'll be able to do anything with GMail (provided less secure apps can access your account, see below).

conn = SMTP('smtp.gmail.com',587)
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.login(username,pwd)
conn.sendmail(username, emailID, message)

Note that after recent changes to GMail, you'll need to explicitly allow less secure apps to access your account. GMail would block your request to login until you enable it. Link to enable less secure apps to access: https://support.google.com/accounts/answer/6010255?hl=en

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
0

Gmail wouldn't let you send an unauthenticated email from an account. Instead, use the Gmail API to send emails. Some useful links below:

Authentication: https://developers.google.com/gmail/api/auth/web-server
Email: https://developers.google.com/gmail/api/guides/sending

yogk
  • 271
  • 5
  • 15