Python实现发送邮件功能(可发送附件)


 在日常工作当中,我们经常要发送一些邮件,比如系统的监控、自动化运维、网站注册后的确认信等各种方面。我们可以通过Python的smtplib模块轻松的实现发送电子邮件。
    smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
    SMTP类构造函数,表示与SMTP服务器之间的连接,通过这个连接我们可以向SMTP服务器发送指令,执行相关操作(如:登陆、发送邮件)。该类提供了许多方法,将在下面介绍。它的所有参数都是可选的,其中host参数表示SMTP服务器主机名;port表示SMTP服务的端口,默认是25;如果在创建SMTP对象的时候提供了这两个参数,在初始化的时候会自动调用connect方法去连接服务器。
    smtplib模块还提供了SMTP_SSL类和LMTP类,对它们的操作与SMTP基本一致。
    SMTP.set_debuglevel(level)
    设置是否为调试模式。默认为False,即非调试模式,表示不输出任何调试信息。
    SMTP.connect([host[, port]])
    连接到指定的SMTP服务器。参数分别表示SMTP主机和端口。注意: 也可以在host参数中指定端口号(如:smtp.163.com:25),这样就没必要给出port参数。
    SMTP.login(user, password)
    登陆到SMTP服务器。现在几乎所有的SMTP服务器,都必须在验证用户信息合法之后才允许发送邮件。
    SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
    发送邮件。这里要注意一下第三个参数,msg是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意msg的格式。这个格式就是SMTP协议中定义的格式。
    SMTP.quit()
    断开与SMTP服务器的连接,相当于发送"quit"指令。
    Python中可以使用emial模块用来处理邮件消息,包括MIME和其他基于RFC 2822的消息文档。使用这些模块来定义邮件的内容,是非常简单的。
    class email.mime.multipart.MIMEMultipart: 多个MIME对象的集合
    class email.mime.audio.MIMEAudio: MIME音频对象
    class email.mime.image.MIMEImage: MIME二进制文件对象
    class email.mime.text.MIMEText: MIME文本对象
    以上介绍只是对Python中smtplib模块和email模块的基本介绍,详细信息请参考官方手册。OK,下面给出如何使用Python发送可以带附件邮件的示例代码,如下:
1. #!/usr/bin/env python 
2. #-*-coding:utf8-*- 
3. 
4. import os, smtplib, mimetypes 
5. from email.mime.text import MIMEText 
6. from email.mime.image import MIMEImage 
7. from email.mime.multipart import MIMEMultipart 
8. 
9. MAIL_LIST = ["username@51cto.com"] 
10. MAIL_HOST = "smtp.51cto.com"
11. MAIL_USER = "username"
12. MAIL_PASS = "password"
13. MAIL_POSTFIX = "51cto.com"
14. MAIL_FROM = MAIL_USER + "<"+MAIL_USER + "@" + MAIL_POSTFIX + ">"
15. 
16. def send_mail(subject, content, filename = None): 
17.     try: 
18.         message = MIMEMultipart() 
19.         message.attach(MIMEText(content)) 
20.         message["Subject"] = subject 
21.         message["From"] = MAIL_FROM 
22.         message["To"] = ";".join(MAIL_LIST) 
23.         if filename != None and os.path.exists(filename): 
24.             ctype, encoding = mimetypes.guess_type(filename) 
25.             if ctype is None or encoding is not None: 
26.                 ctype = "application/octet-stream"
27.             maintype, subtype = ctype.split("/", 1) 
28.             attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype) 
29.             attachment.add_header("Content-Disposition", "attachment", filename = filename) 
30.             message.attach(attachment) 
31. 
32.         smtp = smtplib.SMTP() 
33.         smtp.connect(MAIL_HOST) 
34.         smtp.login(MAIL_USER, MAIL_PASS) 
35.         smtp.sendmail(MAIL_FROM, MAIL_LIST, message.as_string()) 
36.         smtp.quit() 
37. 
38.         return True
39.     except Exception, errmsg: 
40.         print "Send mail failed to: %s" % errmsg 
41.         return False
42. 
43. if __name__ == "__main__": 
44.     if send_mail("测试信", "我的博客欢迎您/", r"G:\attachment.rar"): 
45.         print "发送成功!"
46.     else: 
47.         print "发送失败!"

 


摘自 追忆的风筝的BLOG

相关内容

    暂无相关文章

评论关闭