一、概述
最近遇到一個需求,需要使用office365郵箱發送郵件,使用SSL發送會失敗,必須使用TLS加密協議才能發送成功。
二、完整代碼
使用類封裝了一下,功能如下:
1. 支持附件
2. 支持多個發件人
3. 執行TLS
MailTools.py
#!/usr/bin/env python3 # coding: utf-8 import smtplib # 加載smtplib模塊 from email.mime.text import MIMEText from email.utils import formataddr from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication import time class SendMail(object): def __init__(self,sender,title,content): self.sender = sender #發送地址 self.title = title # 標題 self.content = content # 發送內容 self.sys_sender = 'xx@office365.com' # 系統賬戶 self.sys_pwd = '123456' # 系統賬戶密碼 def send(self,file_list): """ 發送郵件 :param file_list: 附件文件列表 :return: bool """ try: # 創建一個帶附件的實例 msg = MIMEMultipart() # 發件人格式 msg['From'] = formataddr(["", self.sys_sender]) # 收件人格式 msg['To'] = formataddr(["", self.sender]) # 郵件主題 msg['Subject'] = self.title # 郵件正文內容 msg.attach(MIMEText(self.content, 'plain', 'utf-8')) # 多個附件 for file_name in file_list: print("file_name",file_name) # 構造附件 xlsxpart = MIMEApplication(open(file_name, 'rb').read()) # filename表示郵件中顯示的附件名 xlsxpart.add_header('Content-Disposition','attachment',filename = '%s'%file_name) msg.attach(xlsxpart) # SMTP服務器 server = smtplib.SMTP("smtp.office365.com", 587,timeout=10) server.ehlo() server.starttls() # 登錄賬戶 server.login(self.sys_sender, self.sys_pwd) # 發送郵件 server.sendmail(self.sys_sender, [self.sender, ], msg.as_string()) # 退出賬戶 server.quit() return True except Exception as e: print(e) return False if __name__ == '__main__': # 發送地址 sender = "12345678@qq.com" # 標題 title = "測試告警" # 開始時間 start_time = time.strftime('%Y-%m-%d %H:%M:%S') ip = "xx.xx.xx.xx" # 發送內容 content = "{} ip: {} 掉線".format(start_time,ip) # 附件列表 file_list = [] ret = SendMail(sender, title, content).send(file_list) print(ret,type(ret))
注意:請根據實際情況,修改郵件賬號和密碼。
