Coder Perfect

How can I use Python to send an email using Gmail as the provider?

Problem

I’m trying to use Python to send email (to Gmail), but I’m receiving the following problem.

Traceback (most recent call last):  
File "emailSend.py", line 14, in <module>  
server.login(username,password)  
File "/usr/lib/python2.5/smtplib.py", line 554, in login  
raise SMTPException("SMTP AUTH extension not supported by server.")  
smtplib.SMTPException: SMTP AUTH extension not supported by server.

The following is the Python script.

import smtplib
fromaddr = 'user_me@gmail.com'
toaddrs  = 'user_you@gmail.com'
msg = 'Why,Oh why!'
username = 'user_me@gmail.com'
password = 'pwd'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

Asked by mahoriR

Solution #1

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"

You must construct an SMTP SSL object if you want to use Port 465:

# SMTP_SSL Example
server_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'

Answered by David Okwii

Solution #2

Before jumping right into STARTTLS, you must first utter EHLO:

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

You should also establish message headers for From:, To:, and Subject:, 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:

To make this work, you must select the “Allow less secure apps” option in your gmail account settings. Otherwise, if gmail detects that a non-Google app is attempting to access to your account, you will receive a “important security alert.”

Answered by MattH

Solution #3

I came across this question when looking for a solution to a similar problem. My user name and password were right, yet I received an SMTP Authentication Error. Here’s what I did to solve it. This is what I read:

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

In a nutshell, Google won’t let you log in using smtplib because it considers it “less secure,” so you’ll need to go to this site while logged in to your Google account and grant access:

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

It should function after it is configured (as shown in the screenshot below).

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')

Is your computer still not working? If you’re still getting the SMTPAuthenticationError, but the code is now 534, the problem is that the location is unknown. Click on the following link:

https://accounts.google.com/DisplayUnlockCaptcha

If you proceed, you should have 10 minutes to register your new app. So go ahead and try again, and it should work this time.

UPDATE: This does not appear to work immediately. You might be stuck for a long with this smptlib error:

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

The message instructs you to sign in using your browser:

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')

Go for a coffee after allowing ‘lesssecureapps,’ then return and try the ‘DisplayUnlockCaptcha’ link again. It may take up to an hour for the update to take effect, according to user experience. Then go through the sign-in process once more.

Answered by radtek

Solution #4

After that, you’ll need to make a file called sendgmail.py.

Then paste in the following code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# Created By  : Jeromie Kirchoff
# Created Date: Mon Aug 02 17:46:00 PDT 2018
# =============================================================================
# Imports
# =============================================================================
import smtplib

# =============================================================================
# SET EMAIL LOGIN REQUIREMENTS
# =============================================================================
gmail_user = 'THEFROM@gmail.com'
gmail_app_password = 'YOUR-GOOGLE-APPLICATION-PASSWORD!!!!'

# =============================================================================
# SET THE INFO ABOUT THE SAID EMAIL
# =============================================================================
sent_from = gmail_user
sent_to = ['THE-TO@gmail.com', 'THE-TO@gmail.com']
sent_subject = "Where are all my Robot Women at?"
sent_body = ("Hey, what's up? friend!\n\n"
             "I hope you have been well!\n"
             "\n"
             "Cheers,\n"
             "Jay\n")

email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(sent_to), sent_subject, sent_body)

# =============================================================================
# SEND EMAIL OR DIE TRYING!!!
# Details: http://www.samlogic.net/articles/smtp-commands-reference.htm
# =============================================================================

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_app_password)
    server.sendmail(sent_from, sent_to, email_text)
    server.close()

    print('Email sent!')
except Exception as exception:
    print("Error: %s!\n\n" % exception)

If you’re successful, you’ll see something like this:

I put it to the test by sending an email to and from myself.

Answered by JayRizzo

Solution #5

#!/usr/bin/env python


import smtplib

class Gmail(object):
    def __init__(self, email, password):
        self.email = email
        self.password = password
        self.server = 'smtp.gmail.com'
        self.port = 587
        session = smtplib.SMTP(self.server, self.port)        
        session.ehlo()
        session.starttls()
        session.ehlo
        session.login(self.email, self.password)
        self.session = session

    def send_message(self, subject, body):
        ''' This must be removed '''
        headers = [
            "From: " + self.email,
            "Subject: " + subject,
            "To: " + self.email,
            "MIME-Version: 1.0",
           "Content-Type: text/html"]
        headers = "\r\n".join(headers)
        self.session.sendmail(
            self.email,
            self.email,
            headers + "\r\n\r\n" + body)


gm = Gmail('Your Email', 'Password')

gm.send_message('Subject', 'Message')

Answered by Ricky Wilson

Post is based on https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python