1、發送 html 文本內容的郵件
# smtplib 負責發送郵件 import smtplib # MIMEText 負責構造郵件內容 from email.mime.text import MIMEText # Header 是用來構建郵件頭的 from email.header import Header smtpServer= "smtp.163.com" sender = "[email protected]" passWord = "MDZWNINBZEDKXXX" receiver = "[email protected]" subject = "Python email test" # 三個引數:第一個為文本內容,第二個 html 設定文本格式,第三個 utf-8 設定編碼 msg = MIMEText("<html><h1>你好!</h1></html>","html","utf-8") # 定義郵件主題 msg["Subject"] = Header(subject,"utf-8") msg["From"] = Header(sender,"utf-8") msg["To"] = Header(receiver) smtp = smtplib.SMTP() smtp.connect(smtpServer) # 登錄 SMTP 服務器 smtp.login(sender,passWord) # msg.as_string() 把 MIMEText 變成 str 物件 smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()
2、發送帶附件的郵件
import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart smtpServer= "smtp.163.com" sender = "[email protected]" passWord = "MDZWNINBZEDKCXXX" receiver = "[email protected]" subject = "Python email test" # 創建一個帶附件的實體 msg = MIMEMultipart() msg["Subject"] = Header(subject,"utf-8") msg["From"] = Header(sender,"utf-8") msg["To"] = Header(receiver) # log.txt 為報告檔案 file = open("log.txt","rb").read() att = MIMEText(file,"base64","utf-8") # 這里的 filename 定義郵件中顯示什么名字 att["Content-Disposition"] = 'attachment; filename="log.txt"' # 添加檔案到郵件附件中去 msg.attach(att) smtp = smtplib.SMTP() smtp.connect(smtpServer) smtp.login(sender,passWord) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/147668.html
標籤:Python
