使用Python发送Gmail邮件遇无响应/超时问题求助
Python发送Gmail邮件超时/无响应问题排查
初始代码的问题
你的第一版代码存在两个关键问题:
- 未指定正确SMTP端口:使用
smtplib.SMTP("smtp.gmail.com")时默认调用25端口,但Gmail的TLS加密服务端口为587,不指定端口会导致连接缓慢甚至超时。 - 邮件格式不符合RFC标准:
sendmail的msg参数必须遵循邮件格式规范,至少需要包含Subject字段与正确的换行结构,直接传入"Hello"会被服务器拒绝或无法正常投递。
初始代码修正版:
import smtplib my_email = "myemail@gmail.com" password = "Password_i_got_from_gmail_setting_up_an_appPassword" # 指定Gmail TLS加密端口587 connection = smtplib.SMTP("smtp.gmail.com", 587) connection.starttls() connection.login(user=my_email, password=password) # 构建符合标准的邮件内容 msg = """Subject: Test Email Hello from Python! """ connection.sendmail(from_addr=my_email, to_addrs="another_email@gmail.com", msg=msg) connection.close()
更新后代码的核心错误
修改后的代码超时主要由以下问题导致:
- SMTP_SSL端口错误:Gmail的SSL加密SMTP端口为465,你填写的1111是无效端口,直接导致无法建立连接,最终超时。
- 收件人邮箱格式错误:
another_email@gmailcom缺少.,正确格式应为another_email@gmail.com。 - (可选优化)使用
smtp.send_message(em)替代sendmail,更适配EmailMessage对象,无需手动转换为字符串。
修正后的更新版代码:
import smtplib import ssl from email.message import EmailMessage smtp_server = "smtp.gmail.com" sender_email = "myemail@gmail.com" # 修正收件人邮箱格式 receiver_email = "another_email@gmail.com" password = "passwordfromgoogleapppasswords" subject = 'testing' body = """\ Hi there This message is sent from Python. """ em = EmailMessage() em['From'] = sender_email em['To'] = receiver_email em['Subject'] = subject em.set_content(body) context = ssl.create_default_context() # 使用正确的SSL端口465 with smtplib.SMTP_SSL(smtp_server, 465, context=context) as smtp: smtp.login(sender_email, password) # 使用send_message简化发送流程 smtp.send_message(em)
额外注意事项
- 确保已在Google账号中开启两步验证,并正确生成应用专用密码(App Password),普通账号密码无法用于SMTP登录。
- 检查网络环境,确认没有防火墙或代理阻止对Gmail SMTP端口(587或465)的访问。
内容的提问来源于stack exchange,提问作者Evan Welty
相关产品推荐
相关产品推荐

