这两天对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, urllib2
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

username = '156408XXXXX@163.com'
password = 'XXXXXXXX'
sender = username
receivers = ','.join(['10643XXXX2@qq.com'])

# 如名字所示: Multipart就是多个部分
msg = MIMEMultipart()
msg['Subject'] = 'Python mail Test'
msg['From'] = sender
msg['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

验证结果

没有什么比来张图片更有说服力的了。如图

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

错误总结

我遇到的错误如下:

D:\Software\Python2\python.exe E:/Code/Python/MyTestSet/mail/withappedix.py
Traceback (most recent call last):
 File "E:/Code/Python/MyTestSet/mail/withappedix.py", line 51, in <module>
  client.sendmail(sender, receivers, msg.as_string())
 File "D:\Software\Python2\lib\email\message.py", line 137, in as_string
  g.flatten(self, unixfrom=unixfrom)
 File "D:\Software\Python2\lib\email\generator.py", line 83, in flatten
  self._write(msg)
 File "D:\Software\Python2\lib\email\generator.py", line 115, in _write
  self._write_headers(msg)
 File "D:\Software\Python2\lib\email\generator.py", line 164, in _write_headers
  v, maxlinelen=self._maxheaderlen, header_name=h).encode()
 File "D:\Software\Python2\lib\email\header.py", line 410, in encode
  value = self._encode_chunks(newchunks, maxlinelen)
 File "D:\Software\Python2\lib\email\header.py", line 370, in _encode_chunks
  _max_append(chunks, s, maxlinelen, extra)
 File "D:\Software\Python2\lib\email\quoprimime.py", line 97, in _max_append
  L.append(s.lstrip())
AttributeError: 'list' object has no attribute 'lstrip'

Process finished with exit code 1

我的解决办法是

复制代码 代码如下:
receiver parameter was list type. either it should be list converted to string using join method or if it is a single recipient, then pass it as a string only

是的,就是receivers = ','.join(['10XXXXXXXX@qq.com'])。这样就搞定了。

也许,你遇到的错误不是我这个,那么也不用担心,我这里有一份比较齐全的错误码对照表。你可以对照着你的错误码来查找具体的错误原因。这样有的放矢,效率会更高一点的。

在编码的过程中,我也是遇到了很多意想不到的错误。而这些错误的错误码对我们来说是很有用的。这对我们测试代码以及找到其中出错的原因和有帮助。

企业退信的错误码对照表 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。