使用python发送带附件的邮件(转)


from email.Header import Header
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
import smtplib, datetime
#创建一个带附件的实例
msg = MIMEMultipart()
#构造附件
att = MIMEText(open('d:\\tc201.rar', 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="tc201.rar"'
msg.attach(att)
#加邮件头
msg['to'] = 'zhousl@xxx.com'
msg['from'] = 'zhousl@xxx.com'
msg['subject'] = Header('冒烟测试结果 (' + str(datetime.date.today()) + ')', \
                        'gb2312')
#发送邮件
server = smtplib.SMTP('smtp.xxx.com')
server.sendmail(msg['from'], msg['to'], \
                 msg.as_string())
server.close

几个值得注意的地方

1)构造附件时注意采用正确的字符集,这个困惑我好久,开始没有用gb2312,发过去的压缩文件就是坏的;

2)上面的代码中没有包括登录smtp服务器的指令,而Internet上面的smtp服务器一般都是要求认证的,可以通过smtp.login方法进行登陆

3)sendmail方法中的参数to可以是包含多个地址的元组,这样可以发送邮件给多个人了

4)Python2.4以前的版本是不支持gb2312字符集的,要下载安装Python2.4才能跑上面的代码,当然2.4.1肯定会更好一点

 

 

-----------------------------另一种做法------------------------------

一、简单发邮件的代码

写了一个服务器的监控程序,里面用到邮件提醒功能。python sample code里面没有认证的部分,于是查了文档,google了一下,下了如下的smtp发送邮件的函数,支持smtp验证。代码如下:

#!/usr/bin/env python
# -*- coding: gbk -*-
#导入smtplib和MIMEText
import smtplib
from email.mime.text import MIMEText
#############
#要发给谁,这里发给2个人
mailto_list=["aaa@juyimeng.com","bbb@juyimeng.com"]
#####################
#设置服务器,用户名、口令以及邮箱的后缀
mail_host="smtp.126.com"
mail_user="xxx"
mail_pass="yyy"
mail_postfix="126.com"
######################
def send_mail(to_list,sub,content):
   '''
   to_list:发给谁
   sub:主题
   content:内容
   send_mail("aaa@126.com","sub","content")
   '''
   me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
   msg = MIMEText(content)
   msg['Subject'] = sub
   msg['From'] = me
   msg['To'] = ";".join(to_list)
   try:
   s = smtplib.SMTP()
   s.connect(mail_host)
   s.login(mail_user,mail_pass)
   s.sendmail(me, to_list, msg.as_string())
   s.close()
   return True
   except Exception, e:
   print str(e)
   return False
if __name__ == '__main__':
   if send_mail(mailto_list,"subject","content"):
   print "发送成功"
   else:
   print "发送失败"

二、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 -*-2
3
from email.Header import Header4
from email.MIMEText import MIMEText5
from email.MIMEMultipart import MIMEMultipart6
import smtplib, datetime7
8
#创建一个带附件的实例9
msg = MIMEMultipart()10
11
#构造附件12
att = MIMEText(open('d:\\tc201.rar', 'rb').read(), 'base64', 'gb2312')13
att["Content-Type"] = 'application/octet-stream'14
att["Content-Disposition"] = 'attachment; filename="tc201.rar"'15
msg.attach(att)16
17
#加邮件头18
msg['to'] = 'zhousl@xxx.com'19
msg['from'] = 'zhousl@xxx.com'20
msg['subject'] = Header('冒烟测试结果 (' + str(datetime.date.today()) + ')', \21
                        'gb2312')22
#发送邮件23
server = smtplib.SMTP('smtp.xxx.com')24
server.sendmail(msg['from'], msg['to'], \25
                 msg.as_string())26
server.close

4、几个值得注意的地方

1)构造附件时注意采用正确的字符集,这个困惑我好久,开始没有用gb2312,发过去的压缩文件就是坏的;

2)上面的代码中没有包括登录smtp服务器的指令,而Internet上面的smtp服务器一般都是要求认证的,可以通过smtp.login方法进行登陆

3)sendmail方法中的参数to可以是包含多个地址的元组,这样可以发送邮件给多个人了

4)Python2.4以前的版本是不支持gb2312字符集的,要下载安装Python2.4才能跑上面的代码,当然2.4.1肯定会更好一点