1. 程式人生 > >python之發送HTML內容的郵件

python之發送HTML內容的郵件

close pytho clas server nbsp string cnblogs n) 郵箱

 1 # 發送html內容的郵件
 2 import smtplib, time, os
 3 from email.mime.text import MIMEText
 4 from email.header import Header
 5 
 6 
 7 def send_mail_html(file):
 8     ‘‘‘發送html內容郵件‘‘‘
 9     # 發送郵箱
10     sender = [email protected]
11     # 接收郵箱
12     receiver = [email protected]
13 # 發送郵件主題 14 t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 15 subject = 自動化測試結果_ + t 16 # 發送郵箱服務器 17 smtpserver = 192.168.20.190 18 # 發送郵箱用戶/密碼 19 username = zhangkai 20 password = 123456 21 22 # 讀取html文件內容 23 f = open(file, rb) 24 mail_body = f.read()
25 f.close() 26 27 # 組裝郵件內容和標題,中文需參數‘utf-8’,單字節字符不需要 28 msg = MIMEText(mail_body, _subtype=html, _charset=utf-8) 29 msg[Subject] = Header(subject, utf-8) 30 msg[From] = sender 31 msg[To] = receiver 32 # 登錄並發送郵件 33 try: 34 smtp = smtplib.SMTP() 35 smtp.connect(smtpserver)
36 smtp.login(username, password) 37 smtp.sendmail(sender, receiver, msg.as_string()) 38 except: 39 print("郵件發送失敗!") 40 else: 41 print("郵件發送成功!") 42 finally: 43 smtp.quit() 44 45 46 def find_new_file(dir): 47 ‘‘‘查找目錄下最新的文件‘‘‘ 48 file_lists = os.listdir(dir) 49 file_lists.sort(key=lambda fn: os.path.getmtime(dir + "\\" + fn) 50 if not os.path.isdir(dir + "\\" + fn) 51 else 0) 52 # print(‘最新的文件為: ‘ + file_lists[-1]) 53 file = os.path.join(dir, file_lists[-1]) 54 print(完整文件路徑:, file) 55 return file 56 57 58 dir = D:\\test_data\\auto_test_result # 指定文件目錄 59 file = find_new_file(dir) # 查找最新的html文件 60 send_mail_html(file) # 發送html內容郵件

python之發送HTML內容的郵件