首页 > 编程 > Python > 正文

Python实现Smtplib发送带有各种附件的邮件实例

2020-02-16 01:39:23
字体:
来源:转载
供稿:网友

这两天对Python的邮件模块比较感兴趣,于是就查了查资料。同时在实际的编码过程中也遇到了各种各样的问题。下面我就来分享一下我与smtplib的故事。

前提条件

我的上一篇博文里面讲解了,发送邮件必须的条件。这里同样是适用的。大致就是要开启邮箱的SMPT/POP服务等等。

核心知识点

因为今天主要讲解的是如何发送带有附件的邮件,那么核心肯定是附件了。怎么才能发附件呢?

其实我们换个思路,就不难理解了。因为我们发送邮件,经过了应用层–>> 传输层–>> 网络层–>>数据链路层–>>物理层。这一系列的步骤,全都变成了比特流了。所以无论是纯文本,图片,亦或是其他类型的文件。在比特流的面前,都是平等的。所以我们发送附件,也是按照发送纯文本的模式来做就行,只不过加上一些特殊的标记即可。

/# 首先是xlsx类型的附件xlsxpart = MIMEApplication(open('test.xlsx', 'rb').read())xlsxpart.add_header('Content-Disposition', 'attachment', filename='test.xlsx')msg.attach(xlsxpart)/# jpg类型的附件jpgpart = MIMEApplication(open('beauty.jpg', 'rb').read())jpgpart.add_header('Content-Disposition', 'attachment', filename='beauty.jpg')msg.attach(jpgpart)/# mp3类型的附件mp3part = MIMEApplication(open('kenny.mp3', 'rb').read())mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3')msg.attach(mp3part)

经过这三小段的代码,想必你已经很清楚了吧。无非就是使用MIMEApplication进行包装一下,然后设置一下内容。最后添加到邮件内容。就是这几步,就搞定了。

完整的代码

# coding:utf-8#  __author__ = 'Mark sinoberg'#  __date__ = '2016/5/26'#  __Desc__ = 实现发送带有各种附件类型的邮件import urllib, urllib2import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.application import MIMEApplicationusername = '156408XXXXX@163.com'password = 'XXXXXXXX'sender = usernamereceivers = ','.join(['10643XXXX2@qq.com'])# 如名字所示: Multipart就是多个部分msg = MIMEMultipart()msg['Subject'] = 'Python mail Test'msg['From'] = sendermsg['To'] = receivers# 下面是文字部分,也就是纯文本puretext = MIMEText('我是纯文本部分,')msg.attach(puretext)# 下面是附件部分 ,这里分为了好几个类型# 首先是xlsx类型的附件xlsxpart = MIMEApplication(open('test.xlsx', 'rb').read())xlsxpart.add_header('Content-Disposition', 'attachment', filename='test.xlsx')msg.attach(xlsxpart)# jpg类型的附件jpgpart = MIMEApplication(open('beauty.jpg', 'rb').read())jpgpart.add_header('Content-Disposition', 'attachment', filename='beauty.jpg')msg.attach(jpgpart)# mp3类型的附件mp3part = MIMEApplication(open('kenny.mp3', 'rb').read())mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3')msg.attach(mp3part)## 下面开始真正的发送邮件了try:  client = smtplib.SMTP()  client.connect('smtp.163.com')  client.login(username, password)  client.sendmail(sender, receivers, msg.as_string())  client.quit()  print '带有各种附件的邮件发送成功!'except smtplib.SMTPRecipientsRefused:  print 'Recipient refused'except smtplib.SMTPAuthenticationError:  print 'Auth error'except smtplib.SMTPSenderRefused:  print 'Sender refused'except smtplib.SMTPException,e:  print e.message            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表