Python 使用office365郵箱的示例
一、概述
最近遇到一個需求,需要使用office365郵箱發送郵件,使用SSL發送會失敗,必須使用TLS加密協議才能發送成功。
二、完整代碼
使用類封裝了一下,功能如下:
1. 支持附件
2. 支持多個發件人
3. 執行TLS
MailTools.py
#!/usr/bin/env python3# coding: utf-8import smtplib # 加載smtplib模塊from email.mime.text import MIMETextfrom email.utils import formataddrfrom email.mime.multipart import MIMEMultipartfrom email.mime.application import MIMEApplicationimport timeclass SendMail(object): def __init__(self,sender,title,content): self.sender = sender #發送地址 self.title = title # 標題 self.content = content # 發送內容 self.sys_sender = ’[email protected]’ # 系統賬戶 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 Falseif __name__ == ’__main__’: # 發送地址 sender = '[email protected]' # 標題 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))
注意:請根據實際情況,修改郵件賬號和密碼。
以上就是Python 使用office365郵箱的示例的詳細內容,更多關于python 使用office郵箱的資料請關注好吧啦網其它相關文章!
相關文章: