You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI用户认证发验证邮件时SMTP报530 STARTTLS缺失错误如何解决

问题原因分析
  • 第一个smtplib.SMTPSenderRefused错误:你最后调用SMTP(settings.EMAIL_HOST).send_message(message)时,新建的SMTP实例完全没有执行过TLS初始化、登录操作,相当于直接用未加密的连接发信,被Gmail服务器拒绝。
  • 第二个TypeError: ehlo() missing 1 required positional argument: 'self'错误:ehlo()、starttls()、login()都是SMTP类的实例方法,不能直接通过类本身调用,必须先实例化SMTP对象,再通过实例调用这些方法。
修复方案

修改Mailer类的send_message方法,正确实例化SMTP对象并执行完整的发信流程,推荐使用上下文管理器自动管理连接生命周期:

from smtplib import SMTP
from email.message import EmailMessage
from core.config import Settings
 
settings = Settings()
 
class Mailer:
    @staticmethod
    def send_message(content: str, subject: str, mail_to: str):
        message = EmailMessage()
        message.set_content(content)
        message['Subject'] = subject
        message['From'] = settings.EMAIL_HOST_USER
        message['To'] = mail_to
        # 正确实例化SMTP对象,传入服务器地址和端口
        with SMTP(host=settings.EMAIL_HOST, port=settings.EMAIL_PORT) as smtp:
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()
            smtp.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
            smtp.send_message(message)

    @staticmethod
    def send_confirmation_message(token: str, mail_to: str):
        confirmation_url = f'localhost:8000/registration/verify/{token}'
        message = '''Hi!
Please confirm your registration: {}.'''.format(confirmation_url)
        Mailer.send_message(
            message,
            'Please confirm your registration',
            mail_to
        )
Gmail发信额外配置

当前Gmail默认禁止第三方客户端用账号普通密码直接登录,你需要额外完成两个配置才能正常发信:

  1. 给你的Google账号开启两步验证
  2. 在账号安全设置中生成「应用专用密码」,把生成的16位密码替换你当前配置里的EMAIL_HOST_PASSWORD即可。

内容的提问来源于stack exchange,提问作者dougj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 04:33:00