一、相关模块介绍
发送邮件主要用到了smtplib和email两个模块,这里首先就两个模块进行一下简单的介绍:
1、smtplib模块
smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
SMTP类构造函数,表示与SMTP服务器之间的连接,通过这个连接可以向smtp服务器发送指令,执行相关操作(如:登陆、发送邮件)。所有参数都是可选的。
host:smtp服务器主机名
port:smtp服务的端口,默认是25;如果在创建SMTP对象的时候提供了这两个参数,在初始化的时候会自动调用connect方法去连接服务器。
smtplib模块还提供了SMTP_SSL类和LMTP类,对它们的操作与SMTP基本一致。
smtplib.SMTP提供的方法:
SMTP.set_debuglevel(level):设置是否为调试模式。默认为False,即非调试模式,表示不输出任何调试信息。
SMTP.connect([host[, port]]):连接到指定的smtp服务器。参数分别表示smpt主机和端口。注意: 也可以在host参数中指定端口号(如:smpt.yeah.net:25),这样就没必要给出port参数。
SMTP.docmd(cmd[, argstring]):向smtp服务器发送指令。可选参数argstring表示指令的参数。
SMTP.helo([hostname]) :使用"helo"指令向服务器确认身份。相当于告诉smtp服务器“我是谁”。
SMTP.has_extn(name):判断指定名称在服务器邮件列表中是否存在。出于安全考虑,smtp服务器往往屏蔽了该指令。
SMTP.verify(address) :判断指定邮件地址是否在服务器中存在。出于安全考虑,smtp服务器往往屏蔽了该指令。
SMTP.login(user, password) :登陆到smtp服务器。现在几乎所有的smtp服务器,都必须在验证用户信息合法之后才允许发送邮件。
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :发送邮件。这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是smtp协议中定义的格式。
SMTP.quit() :断开与smtp服务器的连接,相当于发送"quit"指令。(很多程序中都用到了smtp.close(),具体与quit的区别google了一下,也没找到答案。)
2、email模块
emial模块用来处理邮件消息,包括MIME和其他基于RFC 2822 的消息文档。使用这些模块来定义邮件的内容,是非常简单的。其包括的类有(更加详细的介绍可见:http://docs.python.org/library/email.mime.html):
class email.mime.base.MIMEBase(_maintype, _subtype, **_params):这是MIME的一个基类。一般不需要在使用时创建实例。其中_maintype是内容类型,如text或者image。_subtype是内容的minor type 类型,如plain或者gif。 **_params是一个字典,直接传递给Message.add_header()。
class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]:MIMEBase的一个子类,多个MIME对象的集合,_subtype默认值为mixed。boundary是MIMEMultipart的边界,默认边界是可数的。
class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]):MIMEMultipart的一个子类。
class email.mime.audio. MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIME音频对象
class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]):MIME二进制文件对象。
class email.mime.message.MIMEMessage(_msg[, _subtype]):
class email.mime.text.MIMEText(_text[, _subtype[, _charset]]):MIME文本对象,其中_text是邮件内容,_subtype邮件类型,可以是text/plain(普通文本邮件),html/plain(html邮件), _charset编码,可以是gb2312等等。
二、几种邮件的具体实现代码
1、普通文本邮件
普通文本邮件发送的实现,关键是要将MIMEText中_subtype设置为plain。首先导入smtplib和mimetext。创建smtplib.SSL实例,,login后发送,具体代码如下:(python2.7下实现)
# coding=utf-8 import smtplib from email.mime.text import MIMEText from email.header import Header #发送邮箱服务器 smtpserver = 'smtp.qq.com' #发件人邮箱 sender = 'XXX@qq.com' #接收人邮箱 receiver = 'XXX@163.com' #发送邮箱客户端授权码 passwd = 'xxxbnrzxzoexdabh' #发送文本 subject = 'python email test' text = u"这是邮件正文" msg = MIMEText(text,'plain','utf-8') #重点是将_subtype设置为plain msg['Subject'] = Header(subject,'utf-8') msg['to'] = receiver s = smtplib.SMTP_SSL(smtpserver,465) #QQ邮件端口 s.login(user, passwd) s.sendmail(sender, receiver, msg.as_string()) s.quit()执行结果如图所示:
2、html邮件的发送
与text邮件不同之处就是将将MIMEText中_subtype设置为html。具体代码如下:(python2.7下实现)
执行结果如图所示:# coding=utf-8 import smtplib from email.mime.text import MIMEText from email.header import Header #发送邮箱服务器 smtpserver = 'smtp.qq.com' #发件人邮箱 sender = 'xxx@qq.com' #接收人邮箱 receiver = 'xxx@163.com' #发送邮箱客户端授权码 passwd = 'xxxbnrzxzoexdabh' #发送htmlsubject = 'python email test' content = "<a href='http://www.baidu.com'>百度</a>" msg = MIMEText(content,'html','utf-8') msg['subject'] = subject msg['from'] = sender msg['to'] = receiver s = smtplib.SMTP_SSL(smtpserver,465) s.login(user, passwd) s.sendmail(sender, receiver, msg.as_string()) print "send success" s.quit()
3、发送带附件的邮件
发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造。
执行结果如图所示:# coding=utf-8 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart #发送邮箱服务器 smtpserver = 'smtp.qq.com' #发件人邮箱 sender = 'xxx@qq.com' #接收人邮箱 receiver = 'xxx@163.com' #发送邮箱客户端授权码 passwd = 'xxxbnrzxzoexdabh' #发送文本 subject = 'python email test' #创建一个带附件的实例 msg = MIMEMultipart() #构造附件1 file_name1 = open('d:\\test.txt','rb').read() att1 = MIMEText(file_name1,'base64','gb2312')#这里的filename是邮件附件的名字att1['content-disposition'] ='attachment;filename="xfdtest.doc"'msg.attach(att1)#构造附件2file_name2 = open('d:\\test.html','rb').read()att2 = MIMEText(file_name2,'html','utf-8')att2['content-disposition'] ='attachment;filename="xfdtest.html"'msg.attach(att2)#加邮件头msg['subject'] = subjectmsg['from'] = sendermsg['to'] = receiver#发送邮件s = smtplib.SMTP_SSL(smtpserver,465)s.login(user, passwd)s.sendmail(sender, receiver, msg.as_string())print "send success"s.quit()
4、利用MIMEimage发送图片
# coding=utf-8 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage #发送邮箱服务器 smtpserver = 'smtp.qq.com' #发件人邮箱 sender = 'xxx@qq.com' #接收人邮箱 receiver = 'xxx@163.com' #发送邮箱客户端授权码 passwd = 'xxxbnrzxzoexdabh' subject = u'正文和附件都包含图片' msg = MIMEMultipart() msg['subject'] = subject msg['from'] = sender msg['to'] = receiver text = MIMEText('<img src="cid:image1">','html','utf-8') msg.attach(text) file1 = open('d:\\sofa.jpg','rb').read() image = MIMEImage(file1) image.add_header('content-ID','<image1>') msg.attach(image) s = smtplib.SMTP_SSL(smtpserver,465) s.login(user, passwd) s.sendmail(sender, receiver, msg.as_string()) print "send success" s.quit()
执行结果如图所示:
参考博客地址:http://www.cnblogs.com/xiaowuyi/archive/2012/03/17/2404015.html