我试图使用python发送电子邮件(Gmail),但我得到以下错误。

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.

Python脚本如下所示。

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

当前回答

下面是一个Gmail API的例子。虽然比较复杂,但这是我发现在2019年唯一有效的方法。这个例子是从以下例子中获取并修改的:

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

你需要通过谷歌的网站创建一个API接口的项目。接下来,你需要为你的应用程序启用GMAIL API。创建凭证,然后下载这些凭证,保存为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()

其他回答

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

如果你想使用端口465,你必须创建一个SMTP_SSL对象:

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

你需要在直接运行到STARTTLS之前说EHLO:

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

此外,您应该真正创建From:、To:和Subject:消息头,用空行与消息体分隔,并使用CRLF作为EOL标记。

E.g.

msg = "\r\n".join([
  "From: user_me@gmail.com",
  "To: user_you@gmail.com",
  "Subject: Just a message",
  "",
  "Why, oh why"
  ])

注意:

为了做到这一点,你需要在gmail帐户配置中启用“允许不太安全的应用程序”选项。否则,当gmail检测到一个非谷歌应用程序试图登录你的帐户时,你会得到一个“关键安全警报”。

不直接相关,但仍然值得指出的是,我的包试图使发送gmail消息非常快速和轻松。它还试图维护一个错误列表,并试图立即指出解决方案。

它只需要下面的代码来完成你所写的:

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

或者一句话:

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

关于包/安装,请查看git或pip,可用于Python 2和3。

2022年12月更新:

您需要使用应用程序密码,以允许您的应用程序访问您的谷歌帐户。

使用应用程序密码登录:

应用程序密码是一个16位数的密码,给一个不太安全的应用程序或 设备权限以访问您的谷歌帐户。应用程序密码 仅用于已开启两步验证的帐户。

此外,谷歌自2022年5月30日起不允许您的应用程序使用用户名(电子邮件地址)和密码访问您的谷歌帐户。所以现在,你需要用户名(电子邮件地址)和应用程序密码来访问你的谷歌帐户。

不太安全的应用和你的谷歌账户:

为了保证您的账户安全,从2022年5月30日起,谷歌号 long支持使用第三方应用程序或设备来询问您 仅使用您的用户名和登录您的谷歌帐户 密码。

如何生成应用程序密码:

首先,从9个点中点击Account:

然后,点击安全中的应用程序密码。*不要忘记在生成应用程序密码之前打开两步验证,否则您无法生成应用程序密码:

然后,点击其他(自定义名称):

然后,输入你的应用程序名称,然后点击GENERATE:

最后,你可以生成应用程序密码xylnudjdiwpojwzm:

所以,你的代码与上面的应用程序密码如下所示:

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

另外,在Django中,带有上述应用程序密码的settings.py如下所示:

# "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