ChatGPT解决这个技术问题 Extra ChatGPT

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 "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()
Also, for VPN users, if the issue still persists, turn your VPN off. That worked for me.

B
Brad Solomon
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'

Very nice sample thanks. One think I noticed is if I want to use an SSL connection I had to remove server.starttls()
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 - 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
@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 '
If your gmail is secured by Two-Factor Authentication, you must first generate an application specific password --> 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).
r
rkachach

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.


invoking server.sendmail(fromaddr, toaddrs, msg) the second parameter, toaddrs must be a list, toaddrs = ['user_me@gmail.com']
As of August 2014 this now raises smtplib.SMTPAuthenticationError: (534, '5.7.9 Application-specific password required.
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/…
Here's a link on how to mail multiple people: stackoverflow.com/questions/8856117/…
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.
r
radtek

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.

https://i.stack.imgur.com/NwOeS.png

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.


thanks man only problem for me : accounts.google.com/DisplayUnlockCaptcha
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.
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" security.google.com/settings/security/apppasswords as already suggested, and it works like a charm
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.
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 support.google.com/mail/?p=InvalidSecondFactor u13sm8439266qtg.64 - gsmtp') I've used the 16 digits app password in my code. Could anyone help me?
J
JayRizzo

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.

https://i.stack.imgur.com/25f6j.png

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.

https://i.stack.imgur.com/1yPnO.png

Clarification

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

https://i.stack.imgur.com/2I1SB.png


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)?
Thank you @Angelo but yes there is a limit, GMail = 500 emails or 500 recipients / Day ref: support.google.com/mail/answer/22839 G SUITE is different and is 2000 messages / day and can be found here: support.google.com/a/answer/166852 Good Luck!
All others are older posts and may not be working, but this is 100% working. Do generate app passwords. Thanks for the answer
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.
@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.
R
Ricky Wilson

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

If your class has only two methods, one of which is __init__, just use a function.
How would you add an attachment using this method?
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.
L
Luke Dupin

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

smtplib is not fully thread-safe, so it will have issues sending concurrent messages. This is the right approach.
Any idea why I get: googleapiclient.errors.HttpError: <HttpError 403 when requesting [https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json][1] returned "Request had insufficient authentication scopes.">? Credential file is downloaded and Gmail API is enabled.
It sounds like you have a configuration error inside the googleapi console. I don't know how to specifically solve that issue. Sorry.
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) 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.
P
PascalVKooten

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.


i
illright

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

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
Where do you instantiate the email variable?
P
Pedro Lobito

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

Really fantastic answer. Best one of the bunch, super concise. Thank you.
Thanks Pedro, your answer solved it. Btw for anyone using Gsuite with multiple aliases; just add the alias to your gmail account following support.google.com/mail/answer/22370?hl=en and you can send using the alias by replacing <{gmailUser}> with <YourAlias>.
m
miksus

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

Set up 2-step-verification (if not yet set up) Create an Application password 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.


Great job simplifying this. Works like a charm. Kudos.
T
Tim Richardson

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


j
juan Isaza

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

m
mega.venik

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

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


K
Kai - Kazuya Ito

Feb, 2022 Update:

Try 2 things to be able to send Gmail using Python.

Allow less secure apps: ON ↓↓↓ https://myaccount.google.com/lesssecureapps Allow access to your Google account: ON (Tap "Continue") ↓↓↓ https://accounts.google.com/DisplayUnlockCaptcha


S
Shyam Gupta
    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

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.
S
Sam Divya Kumar
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()

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.
This doesn't fix the OP's problem.