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()
share|improve this question
9  
This question should be unlocked now that google is moving toward an internal API for sending messages via gmail. This move makes all but one of these answers outdated, and the one relevant answer is very light on actually solving the problem. – Andrew Dec 30 '16 at 21:34

11 Answers 11

up vote 164 down vote accepted

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"
  ])
share|improve this answer
1  
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 6:59
7  
As of August 2014 this now raises smtplib.SMTPAuthenticationError: (534, '5.7.9 Application-specific password required. – anon58192932 Aug 27 '14 at 18:06
4  
For me though, I had to enable an 'app' password to log in using an @google account to send emails via python: support.google.com/accounts/answer/… – anon58192932 Aug 27 '14 at 18:13
    
Finally, what's the best way to use this syntax to send to multiple addresses at once? – anon58192932 Aug 27 '14 at 18:15
1  
Here's a link on how to mail multiple people: stackoverflow.com/questions/8856117/… – anon58192932 Aug 27 '14 at 18:43
def send_email(user, pwd, recipient, subject, body):
    import smtplib

    gmail_user = user
    gmail_pwd = pwd
    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)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_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'
share|improve this answer
21  
+1 thank you for a full working code! – Alessandro Jacopson Dec 9 '12 at 11:01
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
10  
Doesn't work anymore unfortunately: smtplib.SMTPAuthenticationError: (534, '5.7.14 <accounts.google.com/… ... Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 support.google.com/mail/bin/answer.py?answer=78754 ... Then i got a mail from google, that there has been a suspicious connection attempt. – royskatt Feb 13 '15 at 17:00
8  
@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: security.google.com/settings/security/apppasswords – Jared Apr 15 '15 at 1:14
13  
@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 7 '15 at 21:16

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.

share|improve this answer
2  
YES THANK YOU ! Happened while using flask-mail – Giannis Dec 25 '14 at 16:12
    
thanks man only problem for me : accounts.google.com/DisplayUnlockCaptcha – Limitless isa Jun 27 '15 at 10:56
    
Thanks @radtek. It saved me. – Mani Dec 26 '15 at 5:05
4  
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

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())
share|improve this answer
    
plus 1 because it is better to build a MIME than to hardcode your own format string. Is MIMEMultipart required for a simple text message? Or is the following also correct: stackoverflow.com/a/6270987/895245 – Ciro Santilli 华涌低端人口 六四事件 法轮功 Dec 22 '15 at 12:25

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.

share|improve this answer

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')
share|improve this answer
20  
If your class has only two methods, one of which is __init__, just use a function. – JoeQuery Sep 3 '14 at 19:51
4  
yeah you know me – Walrus the Cat Dec 16 '14 at 17:54
1  
Who's down with OOP? :-) – Helen Neely Nov 4 '16 at 16:03

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

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

share|improve this answer

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

share|improve this answer

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()
share|improve this answer
    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
share|improve this answer
    
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
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()
share|improve this answer
    
simple code to send a mail through gmail using python code. from address is your gmailID and receiveraddress is mail id which u send mail. – Sam Divya Kumar Dec 4 '15 at 14:16

protected by Community Mar 4 '16 at 3:12

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.