使用Python SMTP库发送OTP邮件遇535认证错误求助
使用Python SMTP发送OTP邮件时的认证错误问题
错误日志
Failed to send email: (535, b'5.7.8 Username and Password not accepted. For more information, go to
5.7.8 https://support.google.com/mail/?p=BadCredentials
d75a77b69052e-4746b3106b9sm84101401cf.18 - gsmtp')
127.0.0.1 - - [05/Mar/2025 07:34:22] "PUT /forget_password HTTP/1.1" 200 -
代码片段
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from api.config import PASSWORD, MAIL def send_otp(email, otp): """ Sends an OTP to the specified email address. Args: email (str): The recipient's email address. otp (str): The OTP to be sent. Sends the OTP via email using SMTP. """ sender_email = MAIL sender_password = PASSWORD subject = "Your OTP Code" body = f"Your OTP code is {otp}. It is valid for 10 minutes." message = MIMEMultipart() message["From"] = sender_email message["To"] = email message["Subject"] = subject message.attach(MIMEText(body, "plain")) try: server = smtplib.SMTP("smtp.gmail.com", 587) # server.starttls() # Uncommented this if using TLS server.login(sender_email, sender_password) server.sendmail(sender_email, email, message.as_string()) server.quit() except Exception as e: print(f"Failed to send email: {e}")
已执行的排查步骤
- 验证邮箱和密码正确无误
- 测试了SMTP服务器地址(smtp.gmail.com)和端口(587)
- 确认SMTP认证已启用
内容的提问来源于stack exchange,提问作者Abhishek
相关产品推荐
相关产品推荐

