能否使用Google SMTP开发Python邮件发送应用?网传禁用是否属实?
使用Gmail通过Python发送邮件的可行方案
Google确实在2022年起逐步停止了对普通密码的SMTP支持,但并没有完全禁用Gmail的SMTP服务,你依然可以通过两种合规方式继续用Gmail做Python邮件发送:
方案一:应用专用密码(个人使用首选,简单快捷)
- 前提:你的Gmail账号必须开启两步验证(2FA)
- 操作步骤:
- 登录Google账号安全设置页
- 找到「应用专用密码」(开启2FA后才会显示该选项)
- 生成一个对应邮件应用的专用密码(比如命名为Python Mail App)
- Python代码示例:
import smtplib from email.mime.text import MIMEText # 替换成你的信息 sender_email = "your-gmail@gmail.com" app_password = "生成的应用专用密码" receiver_email = "target@example.com" # 构建邮件 msg = MIMEText("这是Python发送的Gmail测试邮件", "plain", "utf-8") msg["Subject"] = "Gmail SMTP测试" msg["From"] = sender_email msg["To"] = receiver_email # 发送邮件 try: with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server: server.login(sender_email, app_password) server.send_message(msg) print("邮件发送成功") except Exception as e: print(f"发送失败:{str(e)}")
方案二:OAuth2认证(生产环境首选,更安全)
如果你的应用需要批量发送邮件或面向用户,推荐用OAuth2——不需要存储密码,靠令牌授权。
- 核心步骤:
- 在Google Cloud控制台创建项目,启用Gmail API
- 创建OAuth客户端ID,下载
credentials.json配置文件 - 用Google官方库获取授权令牌
- Python代码示例(需先安装
google-auth和google-auth-oauthlib库):
import os import smtplib from email.mime.text import MIMEText from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow # 权限范围 SCOPES = ["https://www.googleapis.com/auth/gmail.send"] def get_auth_creds(): creds = None # 首次授权后会生成token.json,后续直接读取 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: token.write(creds.to_json()) return creds def send_email(): creds = get_auth_creds() sender_email = "your-gmail@gmail.com" receiver_email = "target@example.com" msg = MIMEText("这是OAuth2认证的Gmail测试邮件", "plain", "utf-8") msg["Subject"] = "Gmail OAuth2测试" msg["From"] = sender_email msg["To"] = receiver_email try: with smtplib.SMTP("smtp.gmail.com", 587) as server: server.starttls() server.ehlo() server.login(sender_email, creds.token) server.send_message(msg) print("邮件发送成功") except Exception as e: print(f"发送失败:{str(e)}") if __name__ == "__main__": send_email()
注意事项
- 没开2FA的话,用不了应用专用密码,只能选OAuth2或者开启2FA
- 普通Gmail账号每天最多发500封邮件,批量发送要控制频率,避免触发反垃圾机制
- 如果发送失败,先检查账号安全设置,确认API或应用密码权限正常
内容的提问来源于stack exchange,提问作者Azury
相关产品推荐
相关产品推荐

