330

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

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 Python script is the following.

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()
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
mahoriR
  • 4,377
  • 3
  • 18
  • 27
  • Also, for VPN users, if the issue still persists, turn your VPN off. That worked for me. – Paul Dec 08 '19 at 18:38

17 Answers17

324
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 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'
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
David Okwii
  • 7,352
  • 2
  • 36
  • 29
  • 2
    Very nice sample thanks. One think I noticed is if I want to use an SSL connection I had to remove server.starttls() – Dowlers Apr 14 '14 at 20:13
  • Probably something obvious, but why do I need to pass TO and FROM to the sendmail function if we already have them in the message? Thank you! – Martin Spasov Nov 08 '14 at 16:04
  • 24
    Doesn't work anymore unfortunately: smtplib.SMTPAuthenticationError: (534, '5.7.14 – royskatt Feb 13 '15 at 17:00
  • 20
    @royskatt - all you need to do is create an app password and use it in lieu of your account password. Create an app password here: https://security.google.com/settings/security/apppasswords – Jared Apr 15 '15 at 01:14
  • 19
    @royskatt : I just got a fix for the issue you where facing. Google has a setting to allow access for less secure apps you just have to turn it 'On'. you can get there from : Google-->my account -->Sign-in & security--> Connected apps & sites--> scroll down and you will find 'Allow less secure apps ' – shaleen mohan Aug 07 '15 at 21:16
  • Thanks, although hiding exceptions with a `print` statement is terrible practice. Let them propagate or rethrow appropriately. – gd1 Mar 25 '16 at 17:02
  • The port 465/ssl example is the only python./gmail example that works for me. Amazing! – Tandy Freeman Apr 26 '16 at 09:45
  • Thank you. For port 465 i failed to called ehlo(). Now its working. – Mushir Jun 08 '16 at 05:07
  • 5
    If your gmail is secured by Two-Factor Authentication, you must first [generate an application specific password](https://security.google.com/settings/security/apppasswords?pli=1) --> then use that app-password for in the above example code (this is very important because then you aren't writing your password down anywhere in cleartext AND you can revoke the app-password at any time). – Trevor Boyd Smith Nov 12 '16 at 16:46
  • Is it possible there's an extra `\n` in here? `From: %s\nTo: %s\nSubject: %s\n\n%s`? Deleting the last `\n` made attachments work for me. – Hatshepsut May 26 '17 at 06:45
  • interestingly, if you take out the comma join for recipients and only pass a single email address, the email still sends! even though the string is something like 'j,o,h,n,d,o,e,...'. I only discovered this after looking in my sent folder – 3pitt Feb 08 '18 at 16:54
  • I don't like any of the options available: I have to enable 2-step authentication (which I feel is overkill) in order for google to allow me to create an app password, otherwise it says "The setting you are looking for is not available for your account", but I'm wary of changing the account setting that allows less secure applications. Is there another option? – chadrik Aug 30 '18 at 22:06
  • 2021-12-09: this answer works fine using google app password feature on a 2-factor-authenication account (both SMPT on port 587 and SMPT_SSL on port 465) – spioter Dec 11 '21 at 18:34
  • 1
    Warning: mind your quotes! I use an .ini file to store my email address as user_name="{my_user_id}@gmail.com" and this solution did not work until I removed double quotes in the ini file. That was the quick fix - still deciding how to handle this fun fact. – spioter Dec 11 '21 at 18:38
229

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.

rkachach
  • 16,517
  • 6
  • 42
  • 66
MattH
  • 37,273
  • 11
  • 82
  • 84
  • 2
    invoking server.sendmail(fromaddr, toaddrs, msg) the second parameter, toaddrs must be a list, toaddrs = ['user_me@gmail.com'] – Massimo Fazzolari Aug 20 '13 at 06:59
  • 17
    As of August 2014 this now raises smtplib.SMTPAuthenticationError: (534, '5.7.9 Application-specific password required. – fIwJlxSzApHEZIl Aug 27 '14 at 18:06
  • 10
    For me though, I had to enable an 'app' password to log in using an @google account to send emails via python: https://support.google.com/accounts/answer/185833?hl=en&ctx=ch_DisplayUnlockCaptcha – fIwJlxSzApHEZIl Aug 27 '14 at 18:13
  • Finally, what's the best way to use this syntax to send to multiple addresses at once? – fIwJlxSzApHEZIl Aug 27 '14 at 18:15
  • 1
    Here's a link on how to mail multiple people: http://stackoverflow.com/questions/8856117/how-to-send-email-to-multiple-recipints-using-python-smtplib – fIwJlxSzApHEZIl Aug 27 '14 at 18:43
  • Why `\r\n`? Why not just `\n`? –  Mar 29 '16 at 14:15
  • SMTP specifies CRLF as line ending – MattH Mar 29 '16 at 14:22
  • how would one specify adding an attachment in this case? – Panduranga Rao Sadhu May 11 '16 at 12:12
  • Note: When sending to Gmail, I had to use both `\r\n` but when I sent to Hotmail or a custom host, I didn't have to, I just used a multiline string. With a multiline string, Gmail put it all on one line and didn't read anything after the first header definition. – User May 19 '16 at 06:56
  • SMTPException: STARTTLS extension not supported by server. – Amit Tripathi Oct 19 '16 at 09:54
  • @De̲̳̳ath-Stalke̲̳̳r: Just checked the documentation and tried the code, it's functioning as expected. Perhaps you hit a temporary error or your connection to gmail is being interfered with. – MattH Oct 19 '16 at 09:59
  • The problem is that almost EVERYTHING says to use HELO and doesn't mention EHLO. I wonder what the difference is... –  Oct 27 '16 at 05:11
  • @FoxDonut I started fiddling with SMTP 20 years ago and back then nothing much did 'HELO'. 'EHLO' is an extended helo and is asked by clients wanting an extended response containing server capabilities. – MattH Oct 28 '16 at 22:25
  • 1
    I once logged in to an SMTP server by telnet and sent `EHLO` by typo. After I tried HELO many times but the response was different. It took hours to figure out that EHLO is actually a command that SMTP understand and I did the typo. – Shiplu Mokaddim Jan 26 '17 at 11:03
  • 1
    Why does this work? I found docs explaining that EHLO is an extended hello, but I do not understand how that results in fixing this bug. – Preethi Vaidyanathan Nov 13 '19 at 15:21
  • @P.V. This answer was for a problem that was posted 7 years ago. It was right at the time. SMTP protocol requires the first action of an SMTP connection to be an `HELO` or a `EHLO` from the client. The `smtplib` library is/was a low level library which required you to know how to use the protocol. The only bug was in the OP's code for not starting the connection with an `EHLO`. – MattH Nov 13 '19 at 15:34
  • smtplib is not fully thread-safe, so it will have issues sending concurrent messages. If that's your requirement, use Gmail REST API – dsbajna Mar 18 '20 at 10:07
  • less secure apps is no longer an option, we must use the google api instead – nam Mar 01 '21 at 13:06
  • Link to Gmail Developers API: https://developers.google.com/gmail/api –  Jul 02 '22 at 17:13
151

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.

You many now also need create an app password by following the steps under section "Create & use app passwords" here: support.google.com/accounts/answer/185833

radtek
  • 34,210
  • 11
  • 144
  • 111
  • 1
    thanks man only problem for me : https://accounts.google.com/DisplayUnlockCaptcha – Limitless isa Jun 27 '15 at 10:56
  • 8
    In addition, please leave half an hour to an hour for settings to change. I created a new account, disabled all the added security, and still got the same error. About an hour later, it all worked. – jkgeyti Mar 29 '16 at 14:05
  • Updated, thanks. I knew it could take some time so I wrote "grab a coffee" but thanks for the ball park figure. Added :) – radtek Mar 29 '16 at 17:51
  • 2
    Enabling less secure apps is not possible if you have the "2-Step Verification" enabled. The best and most secure option is to enable the "apppassword" https://security.google.com/settings/security/apppasswords as already suggested, and it works like a charm – Omiod Jul 03 '16 at 07:59
  • 3
    When I follow the apppasswords link, all my Google accounts get a "The setting you are looking for is not available for your account" error. – Suzanne Jun 30 '17 at 20:04
  • 1
    I've done all that is was said all logged in the account that i am using(Less secure enabled + 2-step verification + app password 16 digits + DisplayUnlockCaptch + wait) and I still got this error (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor u13sm8439266qtg.64 - gsmtp') I've used the 16 digits app password in my code. Could anyone help me? – David_Rowie Mar 22 '20 at 04:05
  • @David_Rowie its possible they changed something. If you figure it out, feel free to update the answer. – radtek Mar 26 '20 at 20:55
  • This has worked for me: https://stackoverflow.com/questions/60796006/python-connect-to-gmail-and-send-mail-error-534-invalidsecondfactor?noredirect=1#comment107598974_60796006 – David_Rowie Mar 27 '20 at 04:21
  • 1
    This method is outdated and no longer supported https://support.google.com/accounts/answer/6010255?authuser=2&hl=en&authuser=2&visit_id=637922890124321110-2095046185&p=less-secure-apps&rd=1 – Vincent Casey Jul 01 '22 at 16:34
  • 1
    @VincentCasey, confirmed. Trying to set up an automated email notification with gmail and this is no longer an option. Either Google discovered a way to monetize this or, well maybe they just want to monetize this feature lol. –  Jul 02 '22 at 16:50
39

This Works

Create Gmail APP Password!

After you create that then create a file called sendgmail.py

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

# =============================================================================
# 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 = "Hey Friends!"
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)

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 https://support.google.com/accounts/answer/185833?hl=en 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.

Clarification

Navigate to https://myaccount.google.com/apppasswords and create an APP Password as stated above.

https://myaccount.google.com/apppasswords

JayRizzo
  • 3,234
  • 3
  • 33
  • 49
  • 1
    Fantastic solution and very well explained in the code. Thank you Jay, much appreciated. Dumb question: would you know what's the max limit of emails per day could be sent (with gmail)? – Angelo Feb 28 '19 at 03:23
  • Thank you @Angelo but yes there is a limit, GMail = 500 emails or 500 recipients / Day ref: https://support.google.com/mail/answer/22839 G SUITE is different and is 2000 messages / day and can be found here: https://support.google.com/a/answer/166852 Good Luck! – JayRizzo Mar 01 '19 at 02:15
  • 3
    All others are older posts and may not be working, but this is 100% working. Do generate app passwords. Thanks for the answer – Shubh Aug 23 '19 at 07:30
  • 2
    I'm a little surprised that this solution doesn't have more upvotes. I haven't tried _all_ the others, but I've tried several, and only this one worked out of the box, with 0 tinkering. – mcouthon Apr 15 '20 at 07:51
  • This works but could there be any security issues to this? – otaku Aug 16 '20 at 03:49
  • Is there a way to get a message id of sorts like you would from using the python gmail api? – otaku Aug 16 '20 at 04:12
  • @abhyudayasrinet only as much as the effort you put in. So, How would you define "Secure"? Depending on how you setup your code? who you have hosting you? what company policies you have? Do you have the proper infrastructure? Do you have an All-Star IT Team? Is company loyalty and morale high? Do you have unit tests? Weekly or monthly releases? Do you have a QA team? And so many other things, if you got all that and control 3rd party apps your off to a good start. There are infinite number of security vulnerabilities. :-) We are all searching for the answers. – JayRizzo Aug 16 '20 at 06:27
  • 1
    @abhyudayasrinet Hmmm... Interesting... I'm going to look into that. That could prove to be helpful with checking for data corruption and a few other potential things like automations&/verifications of sorts. – JayRizzo Aug 24 '20 at 06:42
  • Definitely. I wish to use this for emails in automation but the google python apis need a new credentials.json generated each time the account's password is changed which is too much of manual intervention too frequently. I couldn't find a way to use app passwords except this one. Some feedback would be good for maintenance/monitoring – otaku Aug 24 '20 at 21:23
  • Why do weird things start to happen when I wrap this in a function? Works fine if I put this code in its own file and run it directly, but if I call it indirectly from another file or bash script I get a (no subject) subject and the spacing of the body is all weird. Anybody else experience this? – Steve Whitmore Sep 18 '21 at 03:15
  • This method is outdated and no longer supported https://support.google.com/accounts/answer/6010255?authuser=2&hl=en&authuser=2&visit_id=637922890124321110-2095046185&p=less-secure-apps&rd=1 – Vincent Casey Jul 01 '22 at 16:34
  • Hi [@vincent-casey](https://stackoverflow.com/users/13171500/vincent-casey), I just tested my code and using a generated app password and it does work. https://myaccount.google.com/apppasswords I also have 2FA on my account. So I disagree with your statement of "outdated and no longer supported". – JayRizzo Jul 01 '22 at 18:08
  • This works and all the other answers I tried did not! Good answer and thanks @JayRizzo – Sahil Shah Nov 25 '22 at 06:50
  • 1
    As of Jan 8th 2023 this still works. – iceAtNight7 Jan 08 '23 at 06:42
19

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:

https://developers.google.com/gmail/api/guides/sending

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 = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send']

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):
    #try:
    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:
            creds.refresh(Request())
        else:
            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.')
    else:
        print('Labels:')
    for label in labels:
        print(label['name'])

    # Example write
    msg = create_message("from@gmail.com", "to@gmail.com", "Subject", "Msg")
    send_message( service, 'me', msg)

if __name__ == '__main__':
    main()
Luke Dupin
  • 2,275
  • 23
  • 30
  • 1
    smtplib is not fully thread-safe, so it will have issues sending concurrent messages. This is the right approach. – dsbajna Mar 18 '20 at 10:18
  • Any idea why I get: `googleapiclient.errors.HttpError: `? Credential file is downloaded and Gmail API is enabled. – Hrvoje Sep 10 '20 at 01:15
  • It sounds like you have a configuration error inside the googleapi console. I don't know how to specifically solve that issue. Sorry. – Luke Dupin Sep 10 '20 at 05:59
  • 1
    I had the same error `Request had insufficient authentication scopes`. This is apparently because you already have a generated token.pickle from this guide (or any another) https://developers.google.com/gmail/api/quickstart/python Solution: 1. you need to just recreate `token.pickle` with new permissions/SCOPES and run a script again. It will be automatically recreate a `token.pickle` with new permissions. – Давид Шико Jan 01 '21 at 13:59
  • Is there any way I can attach attachments too – farhan jatt Jul 09 '23 at 01:04
18

You down with OOP?

#!/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')
Ricky Wilson
  • 3,187
  • 4
  • 24
  • 29
  • 39
    If your class has only two methods, one of which is \_\_init__, just use a function. – JoeQuery Sep 03 '14 at 19:51
  • How would you add an attachment using this method? – sgerbhctim Apr 14 '19 at 02:51
  • 2
    Using a class would be good if you wanted to init the client and pass it around to other parts of the code, instead of passing around a email and password. Or if you want to send several message without passing in the email and password each time. – Sami Start Sep 10 '19 at 07:07
15

You can find it here: http://jayrambhia.com/blog/send-emails-using-python

smtp_host = 'smtp.gmail.com'
smtp_port = 587
server = smtplib.SMTP()
server.connect(smtp_host,smtp_port)
server.ehlo()
server.starttls()
server.login(user,passw)
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'))
server.sendmail(user,tolist,msg.as_string())
illright
  • 3,991
  • 2
  • 29
  • 54
Froyo
  • 17,947
  • 8
  • 45
  • 73
15

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('user_me@gmail.com')
yag.send('user_you@gmail.com', 'Why,Oh why!')

Or a one liner:

yagmail.SMTP('user_me@gmail.com').send('user_you@gmail.com', 'Why,Oh why!')

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

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
10

Dec, 2022 Update:

You need to use an app password to allow your app to access your google account.

Sign in with App Passwords:

An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on.

In addition, google hasn't allowed your app to access your google account with username(email address) and password since May 30, 2022. So now, you need username(email address) and an app password to access your google account.

Less secure apps & your Google Account:

To help keep your account secure, from May 30, 2022, ​​Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

How to generate an app password:

First, click on Account from 9 dots:

enter image description here

Then, click on App passwords from Security. *Don't forget to turn on 2-Step Verification before generating an app password otherwise you cannot generate an app password:

enter image description here

Then, click on Other (Custom name):

enter image description here

Then, put your app name, then click on GENERATE:

enter image description here

Finally, you could generate the app password xylnudjdiwpojwzm:

enter image description here

So, your code with the app password above is as shown below:

import smtplib

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

In addition, settings.py with the app password above in Django is as shown below:

# "settings.py"

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'myaccount@gmail.com'
EMAIL_HOST_PASSWORD = 'xylnudjdiwpojwzm' # Here
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
5

Realized how painful many of the things are with sending emails via Python thus I made an extensive library for it. It also has Gmail pre-configured (so you don't have to remember Gmail's host and port):

from redmail import gmail
gmail.user_name = "you@gmail.com"
gmail.password = "<YOUR APPLICATION PASSWORD>"

# Send an email
gmail.send(
    subject="An example email",
    receivers=["recipient@example.com"],
    text="Hi, this is text body.",
    html="<h1>Hi, this is HTML body.</h1>"
)

Of course you need to configure your Gmail account (don't worry, it's simple):

  1. Set up 2-step-verification (if not yet set up)
  2. Create an Application password
  3. Put the Application password to the gmail object and done!

Red Mail is actually pretty extensive (include attachments, embed images, send with cc and bcc, template with Jinja etc.) and should hopefully be all you need from an email sender. It is also well tested and documented. I hope you find it useful.

To install:

pip install redmail

Documentation: https://red-mail.readthedocs.io/en/latest/

Source code: https://github.com/Miksus/red-mail

Note that Gmail don't allow changing the sender. The sender address is always you.

miksus
  • 2,426
  • 1
  • 18
  • 34
4

Enable less secure apps on your gmail account and use (Python>=3.6):

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

gmailUser = 'XXXXX@gmail.com'
gmailPassword = 'XXXXX'
recipient = 'XXXXX@gmail.com'

message = f"""
Type your message here...
"""

msg = MIMEMultipart()
msg['From'] = f'"Your Name" <{gmailUser}>'
msg['To'] = recipient
msg['Subject'] = "Subject here..."
msg.attach(MIMEText(message))

try:
    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmailUser, gmailPassword)
    mailServer.sendmail(gmailUser, recipient, msg.as_string())
    mailServer.close()
    print ('Email sent!')
except:
    print ('Something went wrong...')
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • 1
    Really fantastic answer. Best one of the bunch, super concise. Thank you. – Bruce Dean Mar 27 '20 at 03:43
  • Thanks Pedro, your answer solved it. Btw for anyone using Gsuite with multiple aliases; just add the alias to your gmail account following https://support.google.com/mail/answer/22370?hl=en and you can send using the alias by replacing `<{gmailUser}>` with ``. – LucSpan Mar 30 '20 at 15:57
2

There is a gmail API now, which lets you send email, read email and create drafts via REST. Unlike the SMTP calls, it is non-blocking which can be a good thing for thread-based webservers sending email in the request thread (like python webservers). The API is also quite powerful.

  • Of course, email should be handed off to a non-webserver queue, but it's nice to have options.

It's easiest to setup if you have Google Apps administrator rights on the domain, because then you can give blanket permission to your client. Otherwise you have to fiddle with OAuth authentication and permission.

Here is a gist demonstrating it:

https://gist.github.com/timrichardson/1154e29174926e462b7a

Tim Richardson
  • 6,608
  • 6
  • 44
  • 71
2

great answer from @David, here is for Python 3 without the generic try-except:

def send_email(user, password, recipient, subject, body):

    gmail_user = user
    gmail_pwd = password
    FROM = user
    TO = recipient if type(recipient) is 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)

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_user, gmail_pwd)
    server.sendmail(FROM, TO, message)
    server.close()
juan Isaza
  • 3,646
  • 3
  • 31
  • 37
1

Seems like problem of the old smtplib. In python2.7 everything works fine.

Update: Yep, server.ehlo() also could help.

mega.venik
  • 648
  • 6
  • 13
0

This will help you. I use this method


  1. First of all, you must activate "2-step verification" from your Google account. follow the below path:

go to google account -> "security" tab (from left menu) -> find "How you sign in to Google" and then enable "2-step verification"

  1. click on "2-step verification" and then click on "App passwords" at the bottom of the page. Then, click on "select app" and chose "other (custom name)". Then, write a name and click on generate.

  2. save the password which displays on the screen.enter image description here

  3. I used below code, you can confiq and use it.

import os
from email.message import EmailMessage
import ssl
import smtplib
email_sender = 'mohsennavazani@gmail.com' #only gmail
email_password = 'Your password from section 3'
email_receiver = 'mohsennavazani@gmail.com' #any type of email

subject = 'check my website (Mohsennavazani.ir)'

body = """
Hello,
this is a test 

"""

em = EmailMessage()
em['From'] = email_sender
em['To'] =  email_receiver
em['Subject'] = subject
em.set_content(body)

#add a layer of security
context = ssl.create_default_context()

#sending the email
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp: 
    smtp.login(email_sender,email_password)
    smtp.sendmail(email_sender,email_receiver, em.as_string())

5- (optional) if you need to send an email to more that 1 email address, you can use the below code in the last part.

li = ["mohsennavazani@gmail.com", "sbu.ar.mohsen@gmail.com"] 
with smtplib.SMTP_SSL('smtp.gmail.com',465,context=context) as smtp: 
    smtp.login(email_sender,email_password)
    smtp.sendmail(email_sender,li, em.as_string())
Mohsen Navazani
  • 131
  • 1
  • 6
-1
    import smtplib

    fromadd='from@gmail.com'
    toadd='send@gmail.com'

    msg='''hi,how r u'''
    username='abc@gmail.com'
    passwd='password'

    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(username,passwd)

        server.sendmail(fromadd,toadd,msg)
        print("Mail Send Successfully")
        server.quit()

   except:
        print("Error:unable to send mail")

   NOTE:https://www.google.com/settings/security/lesssecureapps that                                                         should be enabled
Shyam Gupta
  • 489
  • 4
  • 8
  • I am posting the simple code that will do how to send mail from Gmail account. If you need any information then let me know. I hope that code will help to all the users. – Shyam Gupta Jun 16 '16 at 19:34
-3
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("fromaddress", "password")
msg = "HI!"
server.sendmail("fromaddress", "receiveraddress", msg)
server.quit()