使用Python自动发送Gmail邮件遇SMTP认证错误,寻求替代方案
解决Gmail第三方应用SMTP认证失败的方案
遇到smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted.')错误,本质是谷歌关闭了普通账号的「不太安全的应用访问」权限,以下是几种可行的解决办法:
1. 使用应用专用密码(App Password)
这是最快捷的方案,但前提是你的谷歌账号已经开启了两步验证:
- 登录谷歌账号,进入「安全」设置页面,找到「两步验证」并完成开启
- 同一页面找到「应用专用密码」,选择生成密码的应用类型(比如「邮件」)和设备(比如「其他」)
- 生成后会得到一个16位的密码,把Python脚本里的原邮箱密码替换成这个专用密码
- SMTP服务器配置保持不变:
smtp.gmail.com,端口587,启用TLS
2. 基于OAuth2.0认证(更安全)
这种方式不需要暴露密码,适合长期使用的脚本:
- 登录谷歌云平台,创建新项目并启用Gmail API
- 在「API和服务」→「凭据」中创建「OAuth客户端ID」,选择「桌面应用」类型
- 下载生成的
credentials.json文件,放到Python脚本同目录下 - 安装依赖库:
pip install google-auth google-auth-oauthlib google-auth-httplib2 - 示例代码:
import smtplib from email.mime.text import MIMEText from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import os.path # 仅需发送邮件的权限 SCOPES = ['https://www.googleapis.com/auth/gmail.send'] def get_auth_credentials(): creds = None # 检查是否已有保存的令牌文件 if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # 令牌无效或过期时刷新/重新获取 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) # 保存令牌供下次使用 with open('token.json', 'w') as token_file: token_file.write(creds.to_json()) return creds def send_gmail(): creds = get_auth_credentials() with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() # 使用OAuth2令牌登录 server.login(creds.user_id, creds.token) # 构造邮件内容 msg = MIMEText('这是一封通过OAuth2认证发送的测试邮件') msg['Subject'] = 'OAuth2测试邮件' msg['From'] = 'your-email@gmail.com' msg['To'] = 'recipient@example.com' # 发送邮件 server.send_message(msg) if __name__ == '__main__': send_gmail()
第一次运行脚本时会弹出浏览器窗口,需要登录谷歌账号授权,之后会自动保存令牌,后续运行无需重复授权。
3. 改用其他邮件服务
如果不想折腾谷歌的认证限制,可以切换到其他支持SMTP的邮件服务:
- Outlook/Hotmail:SMTP服务器
smtp.office365.com,端口587,直接使用账号密码登录 - Yahoo邮箱:SMTP服务器
smtp.mail.yahoo.com,端口587,需开启应用密码(类似谷歌的设置) - 第三方邮件服务:比如SendGrid、Mailgun等,提供更灵活的SMTP接口和更高的发送额度,适合批量发送场景
内容的提问来源于stack exchange,提问作者Christoph Sanders
相关产品推荐
相关产品推荐

