How to send an email with Gmail as provider using Python? How to send an email with Gmail as provider using Python? python python

How to send an email with Gmail as provider using Python?


def send_email(user, pwd, recipient, subject, body):    import smtplib    FROM = user    TO = recipient if isinstance(recipient, list) else [recipient]    SUBJECT = subject    TEXT = body    # Prepare actual message    message = """From: %s\nTo: %s\nSubject: %s\n\n%s    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)    try:        server = smtplib.SMTP("smtp.gmail.com", 587)        server.ehlo()        server.starttls()        server.login(user, pwd)        server.sendmail(FROM, TO, message)        server.close()        print 'successfully sent the mail'    except:        print "failed to send mail"

if you want to use Port 465 you have to create an SMTP_SSL object:

# SMTP_SSL Exampleserver_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)server_ssl.ehlo() # optional, called by login()server_ssl.login(gmail_user, gmail_pwd)  # ssl server doesn't support or need tls, so don't call server_ssl.starttls() server_ssl.sendmail(FROM, TO, message)#server_ssl.quit()server_ssl.close()print 'successfully sent the mail'


You need to say EHLO before just running straight into STARTTLS:

server = smtplib.SMTP('smtp.gmail.com:587')server.ehlo()server.starttls()

Also you should really create From:, To: and Subject: message headers, separated from the message body by a blank line and use CRLF as EOL markers.

E.g.

msg = "\r\n".join([  "From: user_me@gmail.com",  "To: user_you@gmail.com",  "Subject: Just a message",  "",  "Why, oh why"  ])

Note:

In order for this to work you need to enable "Allow less secure apps" option in your gmail account configuration. Otherwise you will get a "critical security alert" when gmail detects that a non-Google apps is trying to login your account.


I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:

https://support.google.com/accounts/answer/6010255

In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:

https://www.google.com/settings/security/lesssecureapps

Once that is set (see my screenshot below), it should work.

enter image description here

Login now works:

smtpserver = smtplib.SMTP("smtp.gmail.com", 587)smtpserver.ehlo()smtpserver.starttls()smtpserver.ehlo()smtpserver.login('me@gmail.com', 'me_pass')

Response after change:

(235, '2.7.0 Accepted')

Response prior:

smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

UPDATE: This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:

235 == 'Authentication successful'503 == 'Error: already authenticated'

The message says to use the browser to sign in:

SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')

After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.