#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
#收件人和发件人
receiver = '188xxxx7275@163.com'
sender = '83xxxx202@qq.com'
#发件人邮箱的SMTP服务器(即sender的SMTP服务器)
smtpserver = 'smtp.qq.com'
#发件人邮箱的用户名和授权码(不是登陆邮箱的密码)
username = '83xxxx202@qq.com'
password = 'moxxxxxxxxxxxfcd' #(83xxxx202@qq.com邮箱的授权码)
mail_title = '有陌生人来访!'
mail_body = '请查看附件图片'
#创建一个实例
message = MIMEText( mail_body, 'plain', 'utf-8' ) #邮件正文
# (plain表示mail_body的内容直接显示,也可以用text,则mail_body的内容在正文中以文本的形式显示,需要下载)
message ['From'] = sender #邮件上显示的发件人
message['To'] = receiver #邮件上显示的收件人
message['Subject'] = Header( mail_title, 'utf-8' ) #邮件主题
smtp = smtplib.SMTP() #创建一个连接
smtp.connect( smtpserver ) #连接发送邮件的服务器
smtp.login( username, password ) #登录服务器
smtp.sendmail( sender, receiver, message.as_string() ) #填入邮件的相关信息并发送
smtp.quit()
运行结果:
D:\Python\python3.exe "D:/PyCharm files/face/raspberry/smtp.py"
Traceback (most recent call last):
File "D:/PyCharm files/face/raspberry/smtp.py", line 43, in <module>
smtp.login( username, password ) #登录服务器
File "D:\Python\lib\smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "D:\Python\lib\smtplib.py", line 631, in auth
(code, resp) = self.docmd("AUTH", mechanism + " " + response)
File "D:\Python\lib\smtplib.py", line 421, in docmd
return self.getreply()
File "D:\Python\lib\smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
解决方案:
在smtp.login(username,password)前面添加两行代码,即可实现邮件成功发送。添加的代码如下:
smtp.ehlo()
smtp.starttls()
在尝试使用Python的smtplib发送邮件时遇到了`smtplib.SMTPServerDisconnected: Connection unexpectedly closed`的问题。错误出现在smtp.login()步骤。为解决此问题,需要在登录服务器之前添加两行代码。具体解决方案是先建立连接并设置TLS安全连接,然后进行登录操作,从而确保邮件成功发送。
1555

被折叠的 条评论
为什么被折叠?



