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

Posted on

Solving problem is about exposing yourself to as many situations as possible like How to send an email with Gmail as provider using Python? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How to send an email with Gmail as provider using Python?, which can be followed any time. Take easy to follow this discuss.

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

I am trying to send email (Gmail) using python, but I am getting following error.

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

The Python script is the following.

import smtplib
fromaddr = ''
toaddrs  = ''
msg = 'Why,Oh why!'
username = ''
password = 'pwd'
server = smtplib.SMTP('')
server.sendmail(fromaddr, toaddrs, msg)
Asked By: Mahori


Answer #1:

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

server = smtplib.SMTP('')

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.


msg = "rn".join([
  "Subject: Just a message",
  "Why, oh why"


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.

Answered By: MattH

Answer #2:

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: %snTo: %snSubject: %snn%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
        server = smtplib.SMTP("", 587)
        server.login(user, pwd)
        server.sendmail(FROM, TO, message)
        print 'successfully sent the mail'
        print "failed to send mail"

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

# SMTP_SSL Example
server_ssl = smtplib.SMTP_SSL("", 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)
print 'successfully sent the mail'
Answered By: David Okwii

Answer #3:

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:

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:

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

enter image description here

Login now works:

smtpserver = smtplib.SMTP("", 587)
smtpserver.login('', '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 atn5.7.8 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:

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 atn5.7.9 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.

Answered By: radtek

Answer #4:

You down with OOP?

#!/usr/bin/env python
import smtplib
class Gmail(object):
    def __init__(self, email, password): = email
        self.password = password
        self.server = ''
        self.port = 587
        session = smtplib.SMTP(self.server, self.port)
        session.login(, self.password)
        self.session = session
    def send_message(self, subject, body):
        ''' This must be removed '''
        headers = [
            "From: " +,
            "Subject: " + subject,
            "To: " +,
            "MIME-Version: 1.0",
           "Content-Type: text/html"]
        headers = "rn".join(headers)
            headers + "rnrn" + body)
gm = Gmail('Your Email', 'Password')
gm.send_message('Subject', 'Message')
Answered By: Ricky Wilson

Answer #5:

This Works

Create Gmail APP Password!

After you create that then create a file called

Then add this 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
# =============================================================================
# =============================================================================
gmail_user = ''
gmail_app_password = 'YOUR-GOOGLE-APPLICATION-PASSWORD!!!!'
# =============================================================================
# =============================================================================
sent_from = gmail_user
sent_to = ['', '']
sent_subject = "Where are all my Robot Women at?"
sent_body = ("Hey, what's up? friend!nn"
             "I hope you have been well!n"
email_text = """
From: %s
To: %s
Subject: %s
""" % (sent_from, ", ".join(sent_to), sent_subject, sent_body)
# =============================================================================
# Details:
# =============================================================================
    server = smtplib.SMTP_SSL('', 465)
    server.login(gmail_user, gmail_app_password)
    server.sendmail(sent_from, sent_to, email_text)
    print('Email sent!')
except Exception as exception:
    print("Error: %s!nn" % exception)

So, if you are successful, will see an image like this:

I tested by sending an email from and to myself.

Successful email sent.

Note: I have 2-Step Verification enabled on my account. App Password works with this! (for gmail smtp setup, you must go to and follow the below steps)

This setting is not available for accounts with 2-Step Verification enabled. Such accounts require an application-specific password for less secure apps access.

Less secure app access... This setting is not available for accounts with 2-Step Verification enabled.

Answered By: JayRizzo

Answer #6:

You can find it here:

smtp_host = ''
smtp_port = 587
server = smtplib.SMTP()
fromaddr = raw_input('Send mail by the name of: ')
tolist = raw_input('To: ').split()
sub = raw_input('Subject: ')
msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = email.Utils.COMMASPACE.join(tolist)
msg['Subject'] = sub
msg.attach(MIMEText(raw_input('Body: ')))
msg.attach(MIMEText('nsent via python', 'plain'))
Answered By: Froyo

Answer #7:

Here is a Gmail API example. Although more complicated, this is the only method I found that works in 2019. This example was taken and modified from:

You’ll need create a project with Google’s API interfaces through their website. Next you’ll need to enable the GMAIL API for your app. Create credentials and then download those creds, save it as credentials.json.

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64
#pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['', '']
def create_message(sender, to, subject, msg):
    message = MIMEText(msg)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    # Base 64 encode
    b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
    b64_string = b64_bytes.decode()
    return {'raw': b64_string}
    #return {'raw': base64.urlsafe_b64encode(message.as_string())}
def send_message(service, user_id, message):
    message = (service.users().messages().send(userId=user_id, body=message).execute())
    print( 'Message Id: %s' % message['id'] )
    return message
    #except errors.HttpError, error:print( 'An error occurred: %s' % error )
def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('gmail', 'v1', credentials=creds)
    # Example read operation
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])
    if not labels:
        print('No labels found.')
    for label in labels:
    # Example write
    msg = create_message("", "", "Subject", "Msg")
    send_message( service, 'me', msg)
if __name__ == '__main__':
Answered By: Luke Dupin

Answer #8:

Not directly related but still worth pointing out is that my package tries to make sending gmail messages really quick and painless. It also tries to maintain a list of errors and tries to point to the solution immediately.

It would literally only need this code to do exactly what you wrote:

import yagmail
yag = yagmail.SMTP('')
yag.send('', 'Why,Oh why!')

Or a one liner:

yagmail.SMTP('').send('', 'Why,Oh why!')

For the package/installation please look at git or pip, available for both Python 2 and 3.

Answered By: PascalVKooten

Leave a Reply

Your email address will not be published.