Gmail更新“Less secure apps”规则后,如何用Python给自己发邮件?
用Python给Gmail发邮件的可行方案(「Less secure apps」禁用后)
Gmail已经彻底禁用了「Less secure apps」选项,之前依赖该设置的Python发邮件方法(比如直接用账号密码通过smtplib连接)已经无法使用,但仍然可以用Python给自己发Gmail,以下是两种靠谱的替代方案:
方案1:使用App Passwords(需开启两步验证)
- 前提条件:你的谷歌账号必须先开启两步验证,否则看不到这个选项
- 操作步骤:
- 登录谷歌账号的安全设置页,找到「App Passwords」入口(只有开启两步验证后才会显示)
- 为你的Python邮件脚本创建一个专属的App Password(比如命名为「Python Email Script」)
- 在代码里用这个生成的16位App Password替换原来的账号密码,配合smtplib使用即可
- 示例代码:
import smtplib from email.mime.text import MIMEText # 替换成你的信息 sender = "your-account@gmail.com" app_pwd = "生成的App Password" receiver = "your-account@gmail.com" # 构建邮件内容 msg = MIMEText("这是用Python发送的测试邮件内容") msg['Subject'] = "Python Gmail测试" msg['From'] = sender msg['To'] = receiver # 发送邮件 try: with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: server.login(sender, app_pwd) server.send_message(msg) print("邮件发送成功!") except Exception as e: print(f"发送失败:{str(e)}")
方案2:使用Gmail API
- 适合需要更复杂邮件操作(比如批量发送、管理邮件)的场景,安全性更高
- 大致流程:
- 去谷歌云平台创建项目,启用Gmail API
- 创建OAuth 2.0客户端ID,下载凭据文件(命名为credentials.json)
- 使用
google-api-python-client库完成授权,调用API发送邮件
- 简化版示例代码:
from googleapiclient.discovery import build from google.oauth2.credentials import Credentials from email.mime.text import MIMEText import base64 # 加载授权凭据(首次运行会弹出浏览器让你授权) creds = Credentials.from_authorized_user_file('credentials.json', ['https://www.googleapis.com/auth/gmail.send']) gmail_service = build('gmail', 'v1', credentials=creds) def build_email(sender, to, subject, content): msg = MIMEText(content) msg['to'] = to msg['from'] = sender msg['subject'] = subject # 编码成API要求的格式 return {'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode()} # 构建并发送邮件 email_msg = build_email("your-account@gmail.com", "your-account@gmail.com", "API测试邮件", "这是通过Gmail API发送的邮件") result = gmail_service.users().messages().send(userId="me", body=email_msg).execute() print(f"邮件已发送,邮件ID:{result['id']}")
更新说明:我将改用Chrome通知,感谢各位的帮助!
内容的提问来源于stack exchange,提问作者averysmalltaco
相关产品推荐
相关产品推荐

