使用smtplib发送邮件,提示smtplib.SMTPServerDisconnected: Connection unexpectedly closed

import smtplib
from email.mime.text import MIMEText
from email.header import Header


smtp_server='smtp.qq.com' # 要发送的服务器
port=465 # 服务器端口号
sender = ''  # 发送邮箱的账号
receivers = ['']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

mail_msg ='<h1>先测试一下</h1>'

message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("测试", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试' # 发送的邮箱主题
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP(smtp_server,port)
    smtpObj.set_debuglevel(1)
    smtpObj.login(sender, sender_password)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
    smtpObj.quit()
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件{}".format(e))

上面有一个坑,因为使用的是QQ邮箱,一般需要先开启 QQ邮箱设置里的各种服务。比如使用pop.qq.com收件,用smtp.qq.com发件,根据需要开启。

开启之后,会看到温馨提示这里有个授权码,一堆七七八八的操作之后得到(因为是重要信息图片处理了)授权码,那么我们需要给发送的邮箱授权。

这里的sender_password就是sender的授权码

import smtplib
from email.mime.text import MIMEText
from email.header import Header


smtp_server='smtp.qq.com' # 要发送的服务器
port=465 # 服务器端口号
sender = ''  # 发送邮箱的账号
sender_password=''  # 发送邮箱的授权码
receivers = ['']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

mail_msg ='<h1>先测试一下</h1>'

message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("测试", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试' # 发送的邮箱主题
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP(smtp_server,port)
    smtpObj.set_debuglevel(1)
    smtpObj.login(sender, sender_password)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
    smtpObj.quit()
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件{}".format(e))

这时候我以为会发送成功,结果报错了:

信息提示是连接关闭,然后检查一下代码,发现需要将smtplib.SMTP()改成smtplib.SMTP_SSL(),smtplib.SMTP()是使用明文传输,对邮件内容不加密,而smtplib.SMTP_SSL()是使用ssl加密方式,通信过程加密,邮件数据安全。

import smtplib
from email.mime.text import MIMEText
from email.header import Header


smtp_server='smtp.qq.com' # 要发送的服务器
port=465 # 服务器端口号
sender = ''  # 发送邮箱的账号
sender_password=''  # 发送邮箱的授权码
receivers = ['']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

mail_msg ='<h1>先测试一下</h1>'

message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("测试", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试' # 发送的邮箱主题
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP_SSL(smtp_server,port)  #将smtplib.SMTP()改成smtplib.SMTP_SSL()
    smtpObj.set_debuglevel(1)
    smtpObj.login(sender, sender_password)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
    smtpObj.quit()
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件{}".format(e))

于是终于发送成功。具体使用还请参考官方文件。

https://docs.python.org/zh-cn/3.7/library/smtplib.html?highlight=email#smtplib.SMTP.quit

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章