如何使用python发送包含正文附件格式和附件的邮件

使用python发送带附件的邮件
1、首先要理解一个常识(RFC)
RFC(The Request for
Comments)是一个关于Internet各种标准的文档,定义了很多的网络协议和数据格式,标准的Internet邮件遵从RFC2822(Internet
Message Format)等几个文档,其中RFC822中描述了邮件头(mail
headers)的格式。具体文档在Python帮助里都可以查到全文。
2、其次要熟悉Python的几个模块
关于邮件的有email,smtplib等,关于编码的有base64,binascii等,发送邮件的方式就是先根据RFC构造好邮件的各个部分,然后登录到smtp服务器sendmail就可以了。
3、下面贴代码
1# -*- coding: cp936 -*-
3from email.Header
import Header
4from email.MIMEText
import MIMEText
5from email.MIMEMultipart
import MIMEMultipart
6import smtplib,
8#创建一个带附件的实例
9msg = MIMEMultipart()
11#构造附件
MIMEText(open('d:\\tc201.rar', 'rb').read(), 'base64',
13att["Content-Type"] =
'application/octet-stream'
14att["Content-Disposition"] =
' filename="tc201.rar"'
15msg.attach(att)
17#加邮件头
18msg['to']
19msg['from']
20msg['subject'] =
Header('冒烟测试结果 (' + str(datetime.date.today()) + ')', \
21&&&&&&&&&&&&&&&&&&&&&&&&'gb2312')
22#发送邮件
23server =
smtplib.SMTP('')
24server.sendmail(msg['from'],
msg['to'], \
25&&&&&&&&&&&&&&&&
msg.as_string())
26server.close
4、几个值得注意的地方
1)构造附件时注意采用正确的字符集,这个困惑我好久,开始没有用gb2312,发过去的压缩文件就是坏的;
2)上面的代码中没有包括登录smtp服务器的指令,而Internet上面的smtp服务器一般都是要求认证的,可以通过smtp.login方法进行登陆
3)sendmail方法中的参数to可以是包含多个地址的元组,这样可以发送邮件给多个人了
4)Python2.4以前的版本是不支持gb2312字符集的,要下载安装Python2.4才能跑上面的代码,当然2.4.1肯定会更好一点
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。& & & & 一、文件形式的邮件& & & & 复制代码代码如下:& & #!/usr/bin/env python3& & #coding: utf-8& & import smtplib& & from email.mime.text import MIMEText& & from email.header import Header& & sender = '***'& & receiver = '***'& & subject = 'python email test'& & smtpserver = ''& & username = '***'& & password = '***'& & msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8',单字节字符不需要& & msg['Subject'] = Header(subject, 'utf-8')& & smtp = smtplib.SMTP()& & smtp.connect('')& & smtp.login(username, password)& & smtp.sendmail(sender, receiver, msg.as_string())& & smtp.quit()& & 二、HTML形式的邮件& & & & 复制代码代码如下:& & #!/usr/bin/env python3& & #coding: utf-8& & import smtplib& & from email.mime.text import MIMEText& & sender = '***'& & receiver = '***'& & subject = 'python email test'& & smtpserver = ''& & username = '***'& & password = '***'& & msg = MIMEText('& & 你好& & ','html','utf-8')& & msg['Subject'] = subject& & smtp = smtplib.SMTP()& & smtp.connect('')& & smtp.login(username, password)& & smtp.sendmail(sender, receiver, msg.as_string())& & smtp.quit()& & 三、带图片的HTML邮件& & & & 复制代码代码如下:& & #!/usr/bin/env python3& & #coding: utf-8& & import smtplib& & from email.mime.multipart import MIMEMultipart& & from email.mime.text import MIMEText& & from email.mime.image import MIMEImage& & sender = '***'& & receiver = '***'& & subject = 'python email test'& & smtpserver = ''& & username = '***'& & password = '***'& & msgRoot = MIMEMultipart('related')& & msgRoot['Subject'] = 'test message'& & msgText = MIMEText('Some HTML text and an image.& & & & good!','html','utf-8')& & msgRoot.attach(msgText)& & fp = open('h:\\python\\1.jpg', 'rb')& & msgImage = MIMEImage(fp.read())& & fp.close()& & msgImage.add_header('Content-ID', '')& & msgRoot.attach(msgImage)& & smtp = smtplib.SMTP()& & smtp.connect('')& & smtp.login(username, password)& & smtp.sendmail(sender, receiver, msgRoot.as_string())& & smtp.quit()& & 四、带附件的邮件& & & & 复制代码代码如下:& & #!/usr/bin/env python3& & #coding: utf-8& & import smtplib& & from email.mime.multipart import MIMEMultipart& & from email.mime.text import MIMEText& & from email.mime.image import MIMEImage& & sender = '***'& & receiver = '***'& & subject = 'python email test'& & smtpserver = ''& & username = '***'& & password = '***'& & msgRoot = MIMEMultipart('related')& & msgRoot['Subject'] = 'test message'& & #构造附件& & att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')& & att["Content-Type"] = 'application/octet-stream'& & att["Content-Disposition"] = ' filename="1.jpg"'& & msgRoot.attach(att)& & smtp = smtplib.SMTP()& & smtp.connect('')& & smtp.login(username, password)& & smtp.sendmail(sender, receiver, msgRoot.as_string())& & smtp.quit()& & 五、群邮件& & & & 复制代码代码如下:& & #!/usr/bin/env python3& & #coding: utf-8& & import smtplib& & from email.mime.text import MIMEText& & sender = '***'& & receiver = ['***','****',……]& & subject = 'python email test'& & smtpserver = ''& & username = '***'& & password = '***'& & msg = MIMEText('你好','text','utf-8')& & msg['Subject'] = subject& & smtp = smtplib.SMTP()& & smtp.connect('')& & smtp.login(username, password)& & smtp.sendmail(sender, receiver, msg.as_string())& & smtp.quit()& & 六、各种元素都包含的邮件& & & & 复制代码代码如下:& & #!/usr/bin/env python3& & #coding: utf-8& & import smtplib& & from email.mime.multipart import MIMEMultipart& & from email.mime.text import MIMEText& & from email.mime.image import MIMEImage& & sender = '***'& & receiver = '***'& & subject = 'python email test'& & smtpserver = ''& & username = '***'& & password = '***'& & # Create message container - the correct MIME type is multipart/alternative.& & msg = MIMEMultipart('alternative')& & msg['Subject'] = "Link"& & # Create the body of the message (a plain-text and an HTML version).& & text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"& & html = """\& & Hi!& & How are you?& & Here is the
you wanted.& & """& & # Record the MIME types of both parts - text/plain and text/html.& & part1 = MIMEText(text, 'plain')& & part2 = MIMEText(html, 'html')& & # Attach parts into message container.& & # According to RFC 2046, the last part of a multipart message, in this case& & # the HTML message, is best and preferred.& & msg.attach(part1)& & msg.attach(part2)& & #构造附件& & att = MIMEText(open('h:\\python\\1.jpg', 'rb').read(), 'base64', 'utf-8')& & att["Content-Type"] = 'application/octet-stream'& & att["Content-Disposition"] = ' filename="1.jpg"'& & msg.attach(att)& & smtp = smtplib.SMTP()& & smtp.connect('')& & smtp.login(username, password)& & smtp.sendmail(sender, receiver, msg.as_string())& & smtp.quit()& & 七、基于SSL的邮件& & 复制代码代码如下:& & #!/usr/bin/env python3& & #coding: utf-8& & import smtplib& & from email.mime.text import MIMEText& & from email.header import Header& & sender = '***'& & receiver = '***'& & subject = 'python email test'& & smtpserver = ''& & username = '***'& & password = '***'& & msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8',单字节字符不需要& & msg['Subject'] = Header(subject, 'utf-8')& & smtp = smtplib.SMTP()& & smtp.connect('')& & smtp.ehlo()& & smtp.starttls()& & smtp.ehlo()& & smtp.set_debuglevel(1)& & smtp.login(username, password)& & smtp.sendmail(sender, receiver, msg.as_string())& & smtp.quit()& & 您可能感兴趣的文章:用smtplib和email封装python发送邮件模块类分享python发送邮件示例(支持中文邮件标题)python发送邮件接收邮件示例分享Python群发邮件实例代码二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)基于python发送邮件的乱码问题的解决办法python发送邮件的实例代码(支持html、图片、附件)& & QQ空间
百度搜藏更多& & Tags:python 邮件& & 复制链接收藏本文打印本文关闭本文返回首页& & 上一篇:sqlalchemy对象转dict的示例& & 下一篇:windows下wxPython开发环境安装与配置方法& & 相关文章python多线程抓取天涯帖子内容示例python实现目录树生成示例Python 调用VC++的动态链接库(DLL)Python pass 语句使用示例python基础教程之udp端口扫描Python ljust rjust center输出Python爬虫框架Scrapy安装使用步骤用python实现的去除win下文本文件头部BOM的代码python list中append()与extend()用法分享35个Python编程小技巧& & 文章评论& & 最 近 更 新& & python访问sqlserver示例Python open读写文件实现脚本python 控制语句python计算程序开始到程序结束的运行时间Python去掉字符串中空格的方法python函数缺省值与引用学习笔记分享python原始套接字编程示例分享Python里隐藏的“禅”删除目录下相同文件的python代码(逐级优化python抓取京东价格分析京东商品价格走势& & 热 点 排 行& & Python入门教程 超详细1小时学会python 中文乱码问题深入分析比较详细Python正则表达式操作指Python字符串的encode与decode研Python open读写文件实现脚本Python enumerate遍历数组示例应Python 深入理解yieldPython+Django在windows下的开发python 文件和路径操作函数小结python 字符串split的用法分享
声明:该文章系网友上传分享,此内容仅代表网友个人经验或观点,不代表本网站立场和观点;若未进行原创声明,则表明该文章系转载自互联网;若该文章内容涉嫌侵权,请及时向
上一篇:下一篇:
相关经验教程
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.001 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.001 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.001 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.005 收益
的原创经验被浏览,获得 ¥0.001 收益
的原创经验被浏览,获得 ¥0.005 收益python读取邮件并下载附件 - 为程序员服务
python读取邮件并下载附件
因需要下载邮件附件,并分析邮件的内容写到数据中。研究了下poplib的收件功能。下面部分代码有参考网上资源。#&coding=utf-8
import&poplib
import&cStringIO
import&email
import&base64
import&datetime
import&time
import&xlrd
from&email&import&parser
import&sys
reload(sys)
sys.setdefaultencoding('gbk')
#########下载邮件附件
def&GetmailAttachment(emailhost,emailuser,emailpass,datestr,keywords):
&&&&host&=&emailhost
&&&&username&=&emailuser
&&&&password&=&emailpass
&&&&keywords&=&keywords&&&#查询的邮件的主题
&&&&datestr&=&datestr&&&&&#查询的邮件日期
&&&&#for&163mail,user&POP3&########&&&
&&&&#&pop_conn&=&poplib.POP3(host)&&&&
&&&&#需要验证的邮件服务
&&&&pop_conn&=&poplib.POP3_SSL(host)
&&&&pop_conn.user(username)
&&&&pop_conn.pass_(password)
&&&&num&=&len(pop_conn.list()[1])&&#邮件总数
&&&&if&num&&&50:&&#当总邮件数目小于50的时候读取所有邮件
&&&&&&&&num2&=&0
&&&&&&&&num2&=&num-50
&&&&for&i&in&range(num,num2,-1):
&&&&&&&&m&=&pop_conn.retr(i)
&&&&&&&&buf&=&cStringIO.StringIO()
&&&&&&&&for&j&in&m[1]:
&&&&&&&&&&&&print&&&&buf,j
&&&&&&&&buf.seek(0)
&&&&&&&&msg&=&email.message_from_file(buf)
&&&&&&&&subject&=&msg.get(&Subject&)
&&&&&&&&date1&=&time.strptime(msg.get(&Date&)[0:24],'%a,&%d&%b&%Y&%H:%M:%S')&#格式化收件时间
&&&&&&&&date2&=&time.strftime(&%Y-%m-%d&,&date1)
&&&&#&&&&&print&date2,subject
&&&&&&&&subjectnew&=&subject.split('?gb2312?B?')&&#gb2312编码邮件的解码
&&&&&&&&try:
&&&&&&&&&&&&cleansubject&=&base64.b64decode(subjectnew[1]).decode('gb2312')
&&&&&&&&except:
&&&&&&&&&&&&pass
&&&&&&&&getfilesuss&=&0
&&&&&&&&if&(date2==datestr)&and&(cleansubject==keywords):
&&&&&&&&&&&&for&part&in&msg.walk():
&&&&&&&&&&&&&&&&contenttype&=&part.get_content_type()
&&&&&&&&&&&&&&&&filename&=&part.get_filename()
&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&if&filename&and&contenttype&==&'application/vnd.ms-excel':&&#我这里需要下载的是excel格式的附件
&&&&&&&&&&&&&&&&&&&&f&=&open(&%s.%s&&%(date2,filename),'wb')
&&&&&&&&&&&&&&&&&&&&f.write(base64.decodestring(part.get_payload()))
&&&&&&&&&&&&&&&&&&&&f.close()
&&&&&&&&&&&&&&&&&&&&print&'文件下载成功'
&&&&&&&&&&&&&&&&&&&&getfilesuss&=&1
&&&&&&&&&&&&&&&&&&&&return&f.name
&&&&&&&&&&&&&&&&else:
&&&&&&&&&&&&&&&&&&&&pass&&&&&&&&&&&&
&&&&&&&&&&&&break
&&&&if&getfilesuss&==&0:
&&&&&&&&print&'未找到符合条件的邮件'
&&&&pop_conn.quit()
博客 - DannySite
原文地址:, 感谢原作者分享。
您可能感兴趣的代码二次元同好交流新大陆
扫码下载App
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
我就是我,认真工作,开心生活!
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
阅读(7096)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
在LOFTER的更多文章
loftPermalink:'',
id:'fks_',
blogTitle:'python发送带附件邮件详解',
blogAbstract:'
python发送邮件
#!/usr/bin/env python#coding=utf-8import timeimport smtplibfrom email.MIMEText import MIMEText#from email.Header import Header#正文 mail_body=\'hello, this is the mail content\'#发信邮箱 '
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}

我要回帖

更多关于 正文元素包含违禁词 的文章

 

随机推荐