运行SMTP代码连接失败,请求协助搭建本地SMTP服务器
一、解决Gmail SMTP连接失败问题
给你列几个必查的点,按顺序排查:
- 指定正确端口:smtp.gmail.com默认用587端口,原代码没加端口参数,很容易超时。修改连接代码:
connection = smtplib.SMTP("smtp.gmail.com", port=587) - 改用App密码登录:Gmail早就禁用了普通密码登录SMTP,必须用「App密码」。前提是你得先给Google账号开启两步验证,然后去账号的「安全」设置里生成专门的App密码,把这个密码替换代码里的password值。
- 检查网络限制:本地防火墙、杀毒软件可能拦截了Python的网络请求,暂时关闭测试下;如果用了代理,得确保代理能正常访问smtp.gmail.com。
- 修正邮件格式:sendmail的msg参数必须符合SMTP标准格式,缺少邮件头会导致发送失败。把msg改成:
msg = """From: jsujith1311@gmail.com To: jsujith1311@gmail.com Subject: Test Email HI"""
二、搭建本地SMTP服务器
推荐两种简单方案,按需选择:
方案1:Python自带模块快速搭建(仅测试用)
Python自带smtpd和asyncore模块,写个脚本就能启动本地SMTP服务器,不会真正发送邮件,只会接收并打印邮件内容:
import asyncore from smtpd import SMTPServer class LocalSMTPServer(SMTPServer): def process_message(self, peer, mailfrom, rcpttos, data): print("Received email:") print(f"From: {mailfrom}") print(f"To: {rcpttos}") print(f"Data:\n{data.decode('utf-8')}") return if __name__ == "__main__": server = LocalSMTPServer(('localhost', 1025), None) print("Local SMTP server running on localhost:1025") try: asyncore.loop() except KeyboardInterrupt: print("\nServer stopped.")
运行脚本后,本地SMTP服务器就在1025端口运行了。测试代码可以这么写:
import smtplib sender = "test@local.com" receiver = "test@local.com" msg = """From: test@local.com To: test@local.com Subject: Local Test Hello from local SMTP!""" with smtplib.SMTP("localhost", 1025) as connection: connection.sendmail(sender, receiver, msg) print("Email sent to local server.")
方案2:可配置的正式SMTP服务器(长期使用)
- Windows:用hMailServer,免费开源,图形界面配置简单,支持POP3、SMTP,能设置域名、邮箱账户、转发规则等。
- Linux/macOS:用Postfix,系统自带或通过包管理器安装(比如Ubuntu下执行
apt install postfix),配置文件在/etc/postfix/main.cf,可设置本地域名、中继等,适合服务器环境。
内容的提问来源于stack exchange,提问作者Sujith Julakanti
相关产品推荐
相关产品推荐

