SMTP是發送郵件的協議,Python內建SMTP的支持,可以發送純文字郵件、HTML郵件以及帶附件的郵件。
Python對SMTP支援有smtplib和email兩個模組,email負責建構郵件,smtplib負責發送郵件。
email.mime.text email.utils msg = MIMEText(message, , ) msg[] = formataddr([,]) msg[] = formataddr([,]) msg[] = server = smtplib.SMTP(, 25 server.login(, server.sendmail(, [ u u == cpu = 100 disk = 500 mem = 50 i range(1 cpu > 90 alert = u disk > 90 alert = u mem > 80 alert = u 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 MIMEApplication27 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对象变成str50 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 = 10057 disk = 50058 mem = 5059 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对象...
【相關推薦】
5. php smtp傳送郵件
7. python smtplib模組傳送SSL/TLS安全郵件實例
以上是Python SMTP郵件模組詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!