侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   145

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

前提条件

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

核心知识点

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

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

\# 首先是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 = '[email protected]'password = 'XXXXXXXX'sender = usernamereceivers = ','.join(['[email protected]'])# 如名字所示: 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

验证结果

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

错误总结

我遇到的错误如下:

D:\Software\Python2\python.exe E:/Code/Python/MyTestSet/mail/withappedix.pyTraceback (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(['[email protected]'])。这样就搞定了。

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

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

企业退信的错误码对照表 

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


  • 上一条:
    Python实现单词翻译功能
    下一条:
    用python写个自动SSH登录远程服务器的小工具(实例)
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中实现字符串可逆性压缩及解压缩功能(0个评论)
    • 使用go + gin + jwt + qrcode实现网站生成登录二维码在app中扫码登录功能(0个评论)
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客