如何在Flask中配置Gmail发邮件权限及解决认证错误
在Flask中使用Gmail发送邮件的解决办法及替代方案
一、使用应用专用密码(推荐,适用于开启两步验证的账号)
- 前提:你的Google账号必须开启两步验证
- 操作步骤:
- 登录Google账号,进入「安全」设置页面
- 找到「应用专用密码」选项(仅开启两步验证后可见)
- 生成新的应用专用密码:选择「邮件」作为应用类型,在「其他(自定义名称)」中输入你的Flask应用标识
- 将生成的16位密码替换Flask-Mail配置里的
MAIL_PASSWORD,原账号密码不再使用 - 确保Flask-Mail核心配置正确:
app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 587 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = '你的Gmail邮箱地址' app.config['MAIL_PASSWORD'] = '生成的应用专用密码'
二、使用Gmail API(更安全,适合生产环境)
若应用专用密码不符合需求,可采用Gmail API方案:
- 操作步骤:
- 登录Google Cloud控制台创建项目,启用Gmail API
- 创建OAuth 2.0客户端ID,选择「桌面应用」类型,下载JSON配置文件
- 借助
google-auth和google-auth-oauthlib库完成授权流程,结合Gmail API发送邮件 - 简化示例代码:
from google.oauth2.credentials import Credentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError # 加载已授权的凭证文件 creds = Credentials.from_authorized_user_file('token.json', ['https://www.googleapis.com/auth/gmail.send']) service = build('gmail', 'v1', credentials=creds) def send_gmail(): try: # 此处需自行实现邮件内容构造逻辑 message = create_email_content('sender@gmail.com', 'recipient@gmail.com', '邮件主题', '邮件正文') service.users().messages().send(userId='me', body=message).execute() except HttpError as error: print(f'发送失败:{error}')
三、替代方案:切换第三方邮件服务
若不想受Gmail安全限制约束,可选用更适配开发场景的邮件服务:
- SendGrid:免费额度满足小型应用需求,支持SMTP或API调用,配置简单
- Mailgun:提供免费开发层级,适合开发阶段及小型生产环境
- Outlook/Hotmail:SMTP服务器为
smtp.office365.com,端口587,开启TLS后直接使用账号密码即可
以SendGrid为例的Flask-Mail配置:
app.config['MAIL_SERVER'] = 'smtp.sendgrid.net' app.config['MAIL_PORT'] = 587 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = 'apikey' app.config['MAIL_PASSWORD'] = '你的SendGrid API密钥'
内容的提问来源于stack exchange,提问作者Vivek
相关产品推荐
相关产品推荐

