Gmail SMTP登录认证失败问题(更新版)
解决Gmail SMTP登录认证失败(535错误)的方案
以下是针对smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted')错误的几种解决方法:
确认账号密码正确性
检查代码中填写的邮箱地址sending@gmail.com是否准确,密码是否为对应账号的正确密码。注意:如果账号开启了两步验证(2FA),普通登录密码无法用于SMTP认证。启用两步验证并使用应用专用密码
- 登录你的Google账号,进入「安全」设置页面,开启两步验证功能。
- 开启后,在安全设置中找到「应用专用密码」选项,生成一个专门用于SMTP服务的密码(选择对应应用类型,比如「邮件」)。
- 将代码中的
your_password替换为这个生成的应用专用密码,重新运行代码。
解除账号安全限制
登录Google账号,查看最近的登录活动记录,如果有来自SMTP登录的异常提示,确认是本人操作后解除安全限制,避免账号被Google的安全机制拦截。改用OAuth2认证方式
若上述方法无效,推荐使用更安全的OAuth2认证替代密码登录,示例代码如下: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_credentials(): 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: # 需要先在Google Cloud Console下载credentials.json 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_test_email(): creds = get_credentials() with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() # 使用OAuth2令牌登录 server.login(creds.user_id, creds.token) # 构造邮件内容 msg = MIMEText('TEST') msg['Subject'] = 'SMTP Test Email' msg['From'] = 'sending@gmail.com' msg['To'] = 'receiving@gmail.com' # 发送邮件 server.send_message(msg) if __name__ == '__main__': send_test_email()使用说明:需先在Google Cloud Console创建项目,启用Gmail API,下载
credentials.json文件放置在代码同级目录下,首次运行会弹出浏览器窗口引导完成认证。
内容的提问来源于stack exchange,提问作者Alan Shiah
相关产品推荐
相关产品推荐

