在Jupyter中使用Python脚本发送邮件(SMTPServerDisconnected: Connection unexpectedly closed)

原文链接:https://www.cnblogs.com/stephenmc/p/8028411.html
文章参考:https://www.jb51.net/article/130411.htm;https://blog.csdn.net/qq_36853469/article/details/87877885

Python脚本发送带附件的邮件代码如下

开发环境:Python3.7
平台:Jupyter notebook

发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。

#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding(‘utf8’)
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
#发送邮件服务器
smtpserver = ‘xxxxx’
#发送邮箱用户名和密码
user = ‘xxxxxx’
password = ‘xxxxxx’
#发送邮箱
sender = ‘xxxxx’
#接受邮箱
receiver = ‘xxxxxxx’
#创建一个带附件的实例
message = MIMEMultipart()
message[‘From’] = Header(‘Python 测试’,‘utf-8’)
message[‘To’] = Header(‘测试’,‘utf-8’)
subject = ‘Python SMTP邮件测试’
message[‘Subject’] = Header(subject,‘utf-8’)
#邮件正文内容
message.attach(MIMEText(‘这是测试Python发送附件功能…’,‘plain’,‘utf-8’))
#构造附件1,传送当前目录下的test.txt文件
att1 = MIMEText(open(‘123.txt’,‘rb’).read(),‘base64’,‘utf-8’)
att1[‘Content-Type’] = ‘application/octet-stream’
#这里的filename可以任意写,写什么名字 邮件中就显示什么名字
att1[‘Content-Disposition’] = ‘attachment;filename:“123.txt”’
message.attach(att1)
smtp = smtplib.SMTP()
smtp.connect(smtpserver,25)
smtp.login(user,password)
smtp.sendmail(sender,receiver,message.as_string())
smtp.quit()

Python脚本发送纯文本的邮件代码如下

#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding(‘utf8’)
import smtplib
from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
#构造纯文本邮件内容
msg = MIMEText(‘hello,send by Python…’,‘plain’,‘utf-8’)
#发送者邮箱
sender = ‘[email protected]
#发送者的登陆用户名和密码
user = ‘[email protected]
password = ‘xxxxxx’
#发送者邮箱的SMTP服务器地址
smtpserver = ‘xxxx’
#接收者的邮箱地址
receiver = [‘[email protected]’,‘[email protected]’] #receiver 可以是一个list
smtp = smtplib.SMTP() #实例化SMTP对象
smtp.connect(smtpserver,25) #(缺省)默认端口是25 也可以根据服务器进行设定
smtp.login(user,password) #登陆smtp服务器
smtp.sendmail(sende

你可能感兴趣的:(Python,Python,Jupyter)