Manas Chaturvedi
Manas Chaturvedi

Reputation: 5540

Sending an email using Python

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 = '[email protected]'
receivers = ['[email protected]']

message = """From: From Person <[email protected]>
To: To Person <[email protected]>
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?

Upvotes: 0

Views: 304

Answers (3)

yogk
yogk

Reputation: 381

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

Upvotes: 0

UltraInstinct
UltraInstinct

Reputation: 44434

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

Upvotes: 2

Malik Brahimi
Malik Brahimi

Reputation: 16711

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

Upvotes: 2

Related Questions