Python發送郵件的模塊類(包括發送文本、HTML、帶附件的郵件)
使用Python腳本進行服務器監控時,當達到告警閥值時,需要郵件通知維護人員進行處理。 本文針對發郵件相關的操作進行了封裝,以方便后續工作中使用。 使用Python發郵件,主要用到smtplib和email兩個模塊。
#!/usr/bin/pythonencoding=utf-8
Filename: send_email.py
from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText
import smtplibclass SendEmail:
# 構造函數:初始化基本信息 def __init__(self, host, user, passwd): lInfo = user.split("@") self._user = user self._account = lInfo[0] self._me = self._account + "<" + self._user + ">" server = smtplib.SMTP() server.connect(host) server.login(self._account, passwd) self._server = server # 發送文件或html郵件 def sendTxtMail(self, to_list, sub, content, subtype='html'): # 如果發送的是文本郵件,則_subtype設置為plain # 如果發送的是html郵件,則_subtype設置為html msg = MIMEText(content, _subtype=subtype, _charset='utf-8') msg['Subject'] = sub msg['From'] = self._me msg['To'] = ";".join(to_list) try: self._server.sendmail(self._me, to_list, msg.as_string()) return True except Exception, e: print str(e) return False # 發送帶附件的文件或html郵件 def sendAttachMail(self, to_list, sub, content, subtype='html'): # 創建一個帶附件的實例 msg = MIMEMultipart() # 增加附件1 att1 = MIMEText(open(r'D:\javawork\PyTest\src\main.py','rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' # 這里的filename可以任意寫,寫什么名字,郵件中顯示什么名字 att1["Content-Disposition"] = 'attachment; filename="main.py"' msg.attach(att1) # 增加附件2 att2 = MIMEText(open(r'D:\javawork\PyTest\src\main.py','rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename="main.txt"' msg.attach(att2) # 增加郵件內容 msg.attach(MIMEText(content, _subtype=subtype, _charset='utf-8')) msg['Subject'] = sub msg['From'] = self._me msg['To'] = ";".join(to_list) try: self._server.sendmail(self._me, to_list, msg.as_string()) return True except Exception, e: print str(e) return False # 發送帶附件的文件或html郵件 def sendImageMail(self, to_list, sub, content, subtype='html'): # 創建一個帶附件的實例 msg = MIMEMultipart() # 增加郵件內容 msg.attach(MIMEText(content, _subtype=subtype, _charset='utf-8')) # 增加圖片附件 image = MIMEImage(open(r'D:\javawork\PyTest\src\test.jpg','rb').read()) #附件列表中顯示的文件名 image.add_header('Content-Disposition', 'attachment;filename=p.jpg') msg.attach(image) msg['Subject'] = sub msg['From'] = self._me msg['To'] = ";".join(to_list) try: self._server.sendmail(self._me, to_list, msg.as_string()) return True except Exception, e: print str(e) return False # 析構函數:釋放資源 def __del__(self): self._server.quit() self._server.close()
mailto_list = ['xxx@163.com'] mail = SendEmail('smtp.163.com', 'xxx@163.com', 'xxxxxx') if mail.sendTxtMail(mailto_list, "測試郵件", "hello world!<br><br><h1>你好,發送文本文件測試<h1>"):
print "發送成功"
else:
print "發送失敗"if mail.sendAttachMail(mailto_list, "測試郵件-帶兩個附件", "hello world!<br><br><h1>你好,發送文本文件測試<h1>"):
print "發送成功"
else:
print "發送失敗"if mail.sendImageMail(mailto_list, "測試郵件-帶一個圖片的附件", "hello world!<br><br><h1>你好,發送文本文件測試<h1>"):
print "發送成功"
else:
print "發送失敗"</pre>