本文實例講述了Python發送郵件測試報告操作。分享給大家供大家參考,具體如下:
發郵件需要用到python兩個模塊,smtplib和email,這倆模塊是python自帶的,只需import即可使用。smtplib模塊主要負責發送郵件,email模塊主要負責構造郵件。其中MIMEText()定義郵件正文,Header()定義郵件標題。MIMEMulipart模塊構造帶附件
發送HTML格式的郵件:
send_email_html.py
import smtplibfrom email.mime.text import MIMEText #MIMEText()定義郵件正文from email.header import Header #Header()定義郵件標題#發送郵箱服務器smtpserver = 'smtp.sina.com'#發送郵箱用戶/密碼(登錄郵箱操作)user = "username@sina.com"password = "password"#發送郵箱sender = "username@sina.com"#接收郵箱receiver = "8888@qq.com"#發送主題subject = 'email by python'#編寫HTML類型的郵件正文(把HTML代碼寫進入)msg = MIMEText('<html><body><a href="">百度一下</a></p></body></html>','html','utf-8')msg['Subject'] = Header(subject,'utf-8')#連接發送郵件(smtplib模塊基本使用格式)smtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(user,password)smtp.sendmail(sender,receiver,msg.as_string())smtp.quit()說明:
smtplib.SMTP():實例化SMTP()connect(host,port):
host:指定連接的郵箱服務器。
port:指定連接服務器的端口號,默認為25.login(user,password):user:登錄郵箱的用戶名。password:登錄郵箱的密碼。sendmail(from_addr,to_addrs,msg,...):
from_addr:郵件發送者地址
to_addrs:郵件接收者地址。字符串列表['接收地址1','接收地址2','接收地址3',...]或'接收地址'
msg:發送消息:郵件內容。一般是msg.as_string(),as_string()是將msg(MIMEText對象或者MIMEMultipart對象)變為str。quit():用于結束SMTP會話。

發送帶附件的郵件
send_email_file.py
import smtplibfrom email.mime.text import MIMEText #MIMRText()定義郵件正文from email.mime.multipart import MIMEMultipart #MIMEMulipart模塊構造帶附件#發送郵件的服務器smtpserver = 'smtp.sina.com'#發送郵件用戶和密碼user ="xxx@sina.com"password = "xxx"#發送者sender = "xxx@sina.com"#接收者receiver = "1xxx@qq.com"#郵件主題subject = "附件的郵件"#發送附件sendfile = open("C://Users//Administrator//Desktop//html5.txt","r").read()att = MIMEText(sendfile,"base64","utf-8")att["Content-Type"] = "application/octet-stream"att["Content-Disposition"] = "attachment;filename = 'html5.txt'"msgRoot = MIMEMultipart('related')msgRoot['Subject'] = subjectmsgRoot.attach(att)smtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(user,password)smtp.sendmail(sender,receiver,msgRoot.as_string())smtp.quit()
新聞熱點
疑難解答