直接回答
- 使用 Python3 通过 SMTP 发送邮件需要
smtplib模块,当前(2025 年)推荐使用 OAuth2 认证,特别是在 Gmail 上,因为基本认证已被禁用。 - 研究表明,使用 Gmail 的 SMTP 需要生成 OAuth2 令牌,步骤包括设置 Google API 项目和使用刷新令牌。
- 证据倾向于建议 Gmail API 作为更安全的选择,但
smtplib仍可行。
背景
SMTP(简单邮件传输协议)是发送电子邮件的标准方式。Python3 的 smtplib 模块允许与 SMTP 服务器通信,但由于 2025 年 Gmail 的安全更新,基本认证(用户名和密码)已不可用,必须使用 OAuth2。
使用 smtplib 和 OAuth2 的步骤
- 创建 OAuth2 凭证:
- 在 Google API Console 创建项目,启用 Gmail API,创建 OAuth 2.0 客户端 ID(选择“桌面应用”),下载
client_secret.json。
- 在 Google API Console 创建项目,启用 Gmail API,创建 OAuth 2.0 客户端 ID(选择“桌面应用”),下载
- 生成令牌:
- 使用工具如 gmail-oauth2-tools 生成访问令牌和刷新令牌。
- 发送邮件:
- 使用生成的令牌通过
smtplib连接到 Gmail SMTP 服务器(地址:smtp.gmail.com,端口:587,使用 TLS)。
- 使用生成的令牌通过
示例代码
以下是使用 smtplib 和 OAuth2 发送邮件的示例:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64
import urllib.parse
import urllib.request
import json
GOOGLE_CLIENT_ID = 'your_client_id'
GOOGLE_CLIENT_SECRET = 'your_client_secret'
GOOGLE_REFRESH_TOKEN = 'your_refresh_token'
def generate_oauth2_string(user, access_token):
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (user, access_token)
return base64.urlsafe_b64encode(auth_string.encode('ascii')).decode('ascii')
def get_access_token():
params = {
'client_id': GOOGLE_CLIENT_ID,
'client_secret': GOOGLE_CLIENT_SECRET,
'refresh_token': GOOGLE_REFRESH_TOKEN,
'grant_type': 'refresh_token'
}
request_url = 'https://accounts.google.com/o/oauth2/token'
response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode('utf-8'))
data = json.loads(response.read().decode('utf-8'))
return data['access_token']
def send_email(sender, to, subject, body):
acce

最低0.47元/天 解锁文章
8480

被折叠的 条评论
为什么被折叠?



