Python內置對SMTP的支持,可以發送純文本郵件、HTML郵件以及帶附件的郵件。
Python對SMTP支持有smtplib和email兩個模塊,email負責構造郵件,smtplib負責發送郵件。
注意:使用前需要開啟SMTP服務
案例:使用163郵箱來結合smtp模塊發送郵件
准備工作:
注冊或者登陸163郵箱,進入“設置”-->“POP3/SMTP/IMAP”,打開“POP3/SMTP服務”,短信驗證后輸入客戶端授權密碼保存
Python代碼:
send_email.py:
import smtplib from email.mime.text import MIMEText from email.header import Header # 發送郵箱服務器
smtpserver = "smtp.163.com"
# 發送郵箱用戶名密碼
user = "nancyrm2018@163.com" password = "輸入自己的客戶端授權密碼"
# 發送和接收郵箱
sender = "nancyrm2018@163.com" receive = "nancyrm2018@126.com"
# 發送郵件主題和內容
subject = "Web Selenium 自動化測試報告" content = "<html><h1 style='color:red'>自動化測試,自學成才</h1></html>"
# HTML郵件正文
msg = MIMEText(content, 'html', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = "nancyrm2018@163.com" msg['To'] = "nancyrm2018@126.com"
# SSL協議端口號要使用465
smtp = smtplib.SMTP_SSL(smtpserver, 465) # HELO向服務器標志用戶身份
smtp.helo(smtpserver) # 服務器返回結果確認
smtp.ehlo(smtpserver) # 登錄郵箱服務器用戶名密碼
smtp.login(user, password) print("Send email start...") smtp.sendmail(sender, receive, msg.as_string()) smtp.quit() print("email send end!")
代碼分析:
我們可以使用SMTP對象的sendmail方法發送郵件,其中部分方法如下:
login(user,password)方法參數說明如下:
- user:登錄郵箱用戶名
- password:登錄郵箱密碼
sendmail(from_addr,to_addrs,msg,..)方法參數說明如下:
- from_addr:郵件發送者地址
- to_addrs:字符串列表,郵件發送地址
- msg:發送信息
除SMTP模塊,還用到了email模塊,主要用來定義郵件的標題和正文:
Header()方法用來定義郵件標題
MIMETText()用於定義郵件正文,參數為html格式的文本。
實現結果:
登錄126郵箱查看,顯示內容如圖:
帶附件的郵件:
Python代碼:
from email.mime.multipart import MIMEMultipart # ... send_file = open(r"E:\python_script\123.png", "rb").read() att = MIMEText(send_file, "base64", 'utf-8') att['Content-Type'] = 'application/octet-stream' att['Content-Disposition'] = 'attachment;filename="logo.png"' msgRoot = MIMEMultipart() msgRoot.attach(MIMEText(content, 'html', 'utf-8')) msgRoot['Subject'] = subject msgRoot['From'] = sender msgRoot['To'] = ','.join(receives) msgRoot.attach(att) #... smtp.sendmail(sender, receives, msgRoot.as_string())