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如何使用Python发送带附件的邮件# -*- coding: cp936 -*-
 2如何使用Python发送带附件的邮件
 3如何使用Python发送带附件的邮件from email.Header import Header
 4如何使用Python发送带附件的邮件from email.MIMEText import MIMEText
 5如何使用Python发送带附件的邮件from email.MIMEMultipart import MIMEMultipart
 6如何使用Python发送带附件的邮件import smtplib, datetime
 7如何使用Python发送带附件的邮件
 8如何使用Python发送带附件的邮件#创建一个带附件的实例
 9如何使用Python发送带附件的邮件msg = MIMEMultipart()
10如何使用Python发送带附件的邮件
11如何使用Python发送带附件的邮件#构造附件
12如何使用Python发送带附件的邮件att = MIMEText(open('d:\\tc201.rar''rb').read(), 'base64''gb2312')
13如何使用Python发送带附件的邮件att["Content-Type"= 'application/octet-stream'
14如何使用Python发送带附件的邮件att["Content-Disposition"= 'attachment; filename="tc201.rar"'
15如何使用Python发送带附件的邮件msg.attach(att)
16如何使用Python发送带附件的邮件
17如何使用Python发送带附件的邮件#加邮件头
18如何使用Python发送带附件的邮件msg['to'= 'zhousl@xxx.com'
19如何使用Python发送带附件的邮件msg['from'= 'zhousl@xxx.com'
20如何使用Python发送带附件的邮件msg['subject'= Header('冒烟测试结果 (' + str(datetime.date.today()) + ')', \
21如何使用Python发送带附件的邮件                        'gb2312')
22如何使用Python发送带附件的邮件#发送邮件
23如何使用Python发送带附件的邮件server = smtplib.SMTP('smtp.xxx.com')
24如何使用Python发送带附件的邮件server.sendmail(msg['from'], msg['to'], \
25如何使用Python发送带附件的邮件                msg.as_string())
26如何使用Python发送带附件的邮件server.close
4、几个值得注意的地方
1)构造附件时注意采用正确的字符集,这个困惑我好久,开始没有用gb2312,发过去的压缩文件就是坏的;
2)上面的代码中没有包括登录smtp服务器的指令,而Internet上面的smtp服务器一般都是要求认证的,可以通过smtp.login方法进行登陆
3)sendmail方法中的参数to可以是包含多个地址的元组,这样可以发送邮件给多个人了
4)Python2.4以前的版本是不支持gb2312字符集的,要下载安装Python2.4才能跑上面的代码,当然2.4.1肯定会更好一点如何使用Python发送带附件的邮件

相关文章: