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

本文介绍了在Jupyter中使用Python通过SMTP发送邮件时遇到的问题,包括SMTPServerDisconnected错误和附件变为.bin文件。解决方案包括调整端口、检查SMTP_SSL使用以及设置附件的Content-Disposition头,确保文件正确显示。
摘要由CSDN通过智能技术生成

原文链接: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 = ‘xxxxx@XXXXX.com.cn’
#发送者的登陆用户名和密码
user = ‘xxxxx@XXXX.com.cn’
password = ‘xxxxxx’
#发送者邮箱的SMTP服务器地址
smtpserver = ‘xxxx’
#接收者的邮箱地址
receiver = [‘xxxxxx@qq.com’,‘xxxxxx@outlook.com’] #receiver 可以是一个list
smtp = smtplib.SMTP() #实例化SMTP对象
smtp.connect(smtpserver,25) #(缺省)默认端口是25 也可以根据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值