Python 使用office365郵箱的示例
一、概述
最近遇到一個(gè)需求,需要使用office365郵箱發(fā)送郵件,使用SSL發(fā)送會(huì)失敗,必須使用TLS加密協(xié)議才能發(fā)送成功。
二、完整代碼
使用類封裝了一下,功能如下:
1. 支持附件
2. 支持多個(gè)發(fā)件人
3. 執(zhí)行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 #發(fā)送地址 self.title = title # 標(biāo)題 self.content = content # 發(fā)送內(nèi)容 self.sys_sender = ’xx@office365.com’ # 系統(tǒng)賬戶 self.sys_pwd = ’123456’ # 系統(tǒng)賬戶密碼 def send(self,file_list): ''' 發(fā)送郵件 :param file_list: 附件文件列表 :return: bool ''' try: # 創(chuàng)建一個(gè)帶附件的實(shí)例 msg = MIMEMultipart() # 發(fā)件人格式 msg[’From’] = formataddr(['', self.sys_sender]) # 收件人格式 msg[’To’] = formataddr(['', self.sender]) # 郵件主題 msg[’Subject’] = self.title # 郵件正文內(nèi)容 msg.attach(MIMEText(self.content, ’plain’, ’utf-8’)) # 多個(gè)附件 for file_name in file_list:print('file_name',file_name)# 構(gòu)造附件xlsxpart = MIMEApplication(open(file_name, ’rb’).read())# filename表示郵件中顯示的附件名xlsxpart.add_header(’Content-Disposition’,’attachment’,filename = ’%s’%file_name)msg.attach(xlsxpart) # SMTP服務(wù)器 server = smtplib.SMTP('smtp.office365.com', 587,timeout=10) server.ehlo() server.starttls() # 登錄賬戶 server.login(self.sys_sender, self.sys_pwd) # 發(fā)送郵件 server.sendmail(self.sys_sender, [self.sender, ], msg.as_string()) # 退出賬戶 server.quit() return True except Exception as e: print(e) return Falseif __name__ == ’__main__’: # 發(fā)送地址 sender = '12345678@qq.com' # 標(biāo)題 title = '測(cè)試告警' # 開(kāi)始時(shí)間 start_time = time.strftime(’%Y-%m-%d %H:%M:%S’) ip = 'xx.xx.xx.xx' # 發(fā)送內(nèi)容 content = '{} ip: {} 掉線'.format(start_time,ip) # 附件列表 file_list = [] ret = SendMail(sender, title, content).send(file_list) print(ret,type(ret))
注意:請(qǐng)根據(jù)實(shí)際情況,修改郵件賬號(hào)和密碼。
以上就是Python 使用office365郵箱的示例的詳細(xì)內(nèi)容,更多關(guān)于python 使用office郵箱的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析2. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML3. python excel和yaml文件的讀取封裝4. python3實(shí)現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)5. python爬蟲(chóng)實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊6. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問(wèn)題及解決7. 詳解docker pull 下來(lái)的鏡像都存到了哪里8. 關(guān)于 Android WebView 的內(nèi)存泄露問(wèn)題10. Python中內(nèi)建模塊collections如何使用
