如何使用 Python 以 Gmail 作为提供商发送电子邮件?

2022-01-17 00:00:00 python email smtp gmail

问题描述

我正在尝试使用 python 发送电子邮件 (Gmail),但出现以下错误.

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.

Python 脚本如下.

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


解决方案

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

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

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


您还应该真正创建 From:To:Subject: 邮件标头,用空行与邮件正文分隔,并且使用 CRLF 作为 EOL 标记.


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 = "
".join([
  "From: user_me@gmail.com",
  "To: user_you@gmail.com",
  "Subject: Just a message",
  "",
  "Why, oh why"
  ])

注意:

为了使其正常工作,您需要启用允许不太安全的应用程序";您的 gmail 帐户配置中的选项.否则,您将收到关键安全警报";当 gmail 检测到非 Google 应用正在尝试登录您的帐户时.

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.

相关文章