python使用smtp发邮件报错:smtplib.SMTPServerDisconnected: Connection unexpectedly closed解决

时间:2024-02-19 16:06:40

python版本:3

邮箱:QQ邮箱,端口465

  

  使用python的smtp模块进行邮件发送,自己测试能成功,但是生产环境会报错:smtplib.SMTPServerDisconnected: Connection unexpectedly closed

 

脚本如下:

import smtplib
from email.mime.text import MIMEText

mailserver = "smtp.qq.com"
username_send = \'hydd@qq.com\'
password = \'frptpssewdsibggc\'
username_recv = \'407387377@qq.com\'
mail = MIMEText(\'成功!\')
mail[\'Subject\'] = \'Python测试\'
mail[\'From\'] = username_send
mail[\'To\'] = username_recv
smtp = smtplib.SMTP(mailserver,port=465)
smtp.login(username_send,password)
smtp.sendmail(username_send,username_recv,mail.as_string())
smtp.quit()
print (\'success\')

 

报错:

C:\Users\HU\Desktop>python test.py
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    smtp = smtplib.SMTP(mailserver,port=465)
  File "C:\Users\HU\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 253, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Users\HU\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 341, in connect
    (code, msg) = self.getreply()
  File "C:\Users\HU\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 398, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

 

  把通过smtp的server地址,端口连接换成通过smtp_ssl连接,即将smtp = smtplib.SMTP(mailserver,port=465)改成smtp = smtplib.SMTP_SSL(mailserver)连接(其中mailserver= ‘smtp.qq.com’),即可成功。