标签:
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 import smtplib 5 from email.mime.text import MIMEText 6 from email.utils import formataddr 7 8 def email(message): 9 #构造MIMEText对象,第一个参数就是邮件正文,第二个参数是MIME的subtype 10 # 传入‘plain‘,最终的MIME就是‘text/plain‘,最后一定要用utf-8编码保证多语言兼容性。 11 msg = MIMEText(message, ‘plain‘, ‘utf-8‘) #message为传入的参数,为发送的消息. 12 """msg = MIMEText(‘<html><body><h1>Hello</h1>‘ + 13 ‘<p>send by <a href="http://www.python.org">Python</a>...</p>‘ + 14 ‘</body></html>‘, ‘html‘, ‘utf-8‘) """ 15 #标准邮件需要三个头部信息: From, To, 和 Subject。 16 msg[‘From‘] = formataddr(["管理员",‘ylemail2012@sina.cn‘]) #显示发件人信息 17 msg[‘To‘] = formataddr(["Saneri",‘349622541@qq.com‘]) #显示收件人信息 18 msg[‘Subject‘] = "Zabbix报警系统!" #定义邮件主题 19 try: 20 #创建SMTP对象 21 server = smtplib.SMTP("smtp.sina.com", 25) 22 #set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息 23 #server.set_debuglevel(1) 24 #login()方法用来登录SMTP服务器 25 server.login("ylemail2012@sina.cn","password") 26 #sendmail()方法就是发邮件,由于可以一次发给多个人,所以传入一个list,邮件正文是一个str,as_string()把MIMEText对象变成str 27 server.sendmail(‘ylemail2012@sina.cn‘, [‘349622541@qq.com‘,], msg.as_string()) 28 print u"邮件发送成功!"
29 server.quit() 30 except smtplib.SMTPException: 31 print u"Error: 无法发送邮件" 32 if __name__ == ‘__main__‘: 33 cpu = 100 34 disk = 500 35 mem = 50 36 for i in range(1): 37 if cpu > 90: 38 alert = u"CPU出问题!" 39 email(alert) 40 if disk > 90: 41 alert = u"硬盘出问题!" 42 email(alert) 43 if mem > 80: 44 alert = u"内存出问题!" 45 email(alert)
#Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html
1 msg = MIMEText(‘<html><body><h1>Hello</h1>‘ + 2 ‘<p>send by <a href="http://www.python.org">Python</a>...</p>‘ + 3 ‘</body></html>‘, ‘html‘, ‘utf-8‘)
发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 import smtplib 5 from email.mime.text import MIMEText 6 from email.utils import formataddr 7 from email.mime.multipart import MIMEMultipart 8 9 def email(message): 10 11 msg = MIMEMultipart() 12 msg[‘From‘] = formataddr(["管理员",‘ylemail2012@sina.cn‘]) 13 msg[‘To‘] = formataddr(["Saneri",‘349622541@qq.com‘]) 14 msg[‘Subject‘] = "Zabbix报警系统!" 15 msg.attach(MIMEText(message, ‘plain‘, ‘utf-8‘)) 16 17 #---这是附件部分--- 18 # 构造附件1,文本类型附件 19 att1 = MIMEText(open(‘test.txt‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) 20 att1["Content-Type"] = ‘application/octet-stream‘ 21 # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 22 att1["Content-Disposition"] = ‘attachment; filename="test.txt"‘ 23 msg.attach(att1) 24 25 # 构造附件2,jpg类型附件 26 from email.mime.application import MIMEApplication 27 att2 = MIMEApplication(open(‘001.jpg‘,‘rb‘).read()) 28 att2.add_header(‘Content-Disposition‘, ‘attachment‘, filename="001.jpg") 29 msg.attach(att2) 30 #构造附件3,pdf类型附件 31 att3 = MIMEApplication(open(‘test.pdf‘,‘rb‘).read()) 32 att3.add_header(‘Content-Disposition‘, ‘attachment‘, filename="test.pdf") 33 msg.attach(att3) 34 #构造附件4,xlsx类型附件 35 att4 = MIMEApplication(open(‘test.xlsx‘,‘rb‘).read()) 36 att4.add_header(‘Content-Disposition‘, ‘attachment‘, filename="test.xlsx") 37 msg.attach(att4) 38 #构造附件5,mp3类型附件 39 att5 = MIMEApplication(open(‘test.mp3‘,‘rb‘).read()) 40 att5.add_header(‘Content-Disposition‘, ‘attachment‘, filename="test.mp3") 41 msg.attach(att5) 42 43 try: 44 server = smtplib.SMTP("smtp.sina.com", 25) 45 #set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息 46 #server.set_debuglevel(1) 47 #login()方法用来登录SMTP服务器 48 server.login("ylemail2012@sina.cn","password") 49 #sendmail()方法就是发邮件,由于可以一次发给多个人,所以传入一个list,邮件正文是一个str,as_string()把MIMEText对象变成str 50 server.sendmail(‘ylemail2012@sina.cn‘, [‘349622541@qq.com‘,], msg.as_string()) 51 print u"邮件发送成功!" 52 server.quit() 53 except smtplib.SMTPException: 54 print u"Error: 无法发送邮件" 55 if __name__ == ‘__main__‘: 56 cpu = 100 57 disk = 500 58 mem = 50 59 for i in range(1): 60 if cpu > 90: 61 alert = u"CPU出问题!" 62 email(alert) 63 if disk > 90: 64 alert = u"硬盘出问题!" 65 email(alert) 66 if mem > 80: 67 alert = u"内存出问题!" 68 email(alert)
邮件的 HTML 文本中一般邮件服务商添加外链是无效的,正确添加突破的实例如下所示:
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 import smtplib 5 from email.mime.multipart import MIMEMultipart 6 from email.mime.text import MIMEText 7 from email.mime.image import MIMEImage 8 from email.utils import formataddr 9 10 def email(): 11 msg = MIMEMultipart() 12 msg[‘From‘] = formataddr(["管理员",‘ylemail2012@sina.cn‘]) 13 msg[‘To‘] = formataddr(["Saneri",‘349622541@qq.com‘]) 14 msg[‘Subject‘] = "Zabbix报警系统!" 15 msg.attach(MIMEText(‘<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!‘,‘html‘,‘utf-8‘)) 16 17 fp = open(‘001.jpg‘, ‘rb‘) 18 msgImage = MIMEImage(fp.read()) 19 fp.close() 20 msgImage.add_header(‘Content-ID‘, ‘<image1>‘) 21 msg.attach(msgImage) 22 try: 23 server = smtplib.SMTP("smtp.sina.com", 25) 24 server.login("ylemail2012@sina.cn","password") 25 server.sendmail(‘ylemail2012@sina.cn‘, [‘349622541@qq.com‘,], msg.as_string()) 26 print u"邮件发送成功!" 27 server.quit() 28 except smtplib.SMTPException: 29 print u"Error: 无法发送邮件" 30 31 if __name__ == ‘__main__‘: 32 email()
如果我们发送HTML邮件,收件人通过浏览器或者Outlook之类的软件是可以正常浏览邮件内容的,但是,如果收件人使用的设备太古老,查看不了HTML邮件怎么办?
办法是在发送HTML的同时再附加一个纯文本,如果收件人无法查看HTML格式的邮件,就可以自动降级查看纯文本邮件。
利用MIMEMultipart
就可以组合一个HTML和Plain,要注意指定subtype是alternative
:
1 msg = MIMEMultipart(‘alternative‘) 2 msg[‘From‘] = ... 3 msg[‘To‘] = ... 4 msg[‘Subject‘] = ... 5 6 msg.attach(MIMEText(‘hello‘, ‘plain‘, ‘utf-8‘)) 7 msg.attach(MIMEText(‘<html><body><h1>Hello</h1></body></html>‘, ‘html‘, ‘utf-8‘)) 8 # 正常发送msg对象...
更多参阅:
http://www.runoob.com/python/python-email.html
标签:
原文地址:http://www.cnblogs.com/saneri/p/5845048.html