前言:
SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協定,它是一組用于由源位址到目的位址傳送郵件的規則,由它來控制信件的中轉方式。
一、Python發送HTML郵件
# -*- coding: utf-8 -*-
# @Time : 2018/6/6 上午11:27
# @Author : Wang
# @File : test_mail_html.py
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendMail():
# 定義相關資料,請更換自己的真實資料
smtpserver = 'smtp.163.com'
sender = '[email protected]'
#receiver可設定多個,使用“,”分隔
receiver = '[email protected],[email protected],[email protected]'
username = '[email protected]'
password = '2018'
msg = MIMEMultipart()
boby = """
<h3>Hi,all</h3>
<p>附件為本次FM_自動化測試報告。</p>
<p>請解壓zip,并使用Firefox打開index.html檢視本次自動化測試報告結果。</p>
"""
mail_body = MIMEText(boby, _subtype='html', _charset='utf-8')
msg['Subject'] = Header("Android_自動化測試報告", 'utf-8')
msg['From'] = sender
receivers = receiver
toclause = receivers.split(',')
msg['To'] = ",".join(toclause)
print(msg['To'])
msg.attach(mail_body)
# 登陸并發送郵件
try:
smtp = smtplib.SMTP()
##打開調試模式
# smtp.set_debuglevel(1)
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, toclause, msg.as_string())
except:
print("郵件發送失敗!!")
else:
print("郵件發送成功")
finally:
smtp.quit()
二、Python發送郵件帶附件
#添加report附件
att = MIMEText(open("/report/html.zip", "rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
times = time.strftime("%m_%d_%H_%M", time.localtime(time.time()))
filename_report = 'FM_Android_Report'+'_'+times+'.zip'
att["Content-Disposition"] = 'attachment; filename= %s ' %filename_report
msg.attach(att)
三、Python發送郵件正文帶圖檔
msg = MIMEMultipart()
boby = """
<h3>Hi,all</h3>
<p>附件為本次FM_自動化測試報告。</p>
<p>請解壓zip,并使用Firefox打開index.html檢視本次自動化測試報告結果。</p>
<p>
<br><img src="cid:image1"></br>
</p>
<p>
"""
msg.attach(mail_body)
fp = open("/image/1.png", 'rb')
images = MIMEImage(fp.read())
fp.close()
images.add_header('Content-ID', '<image1>')
msg.attach(images)
以上~~對你有幫助的話,點贊吧~
作者:
擱淺出處:
http://www.cnblogs.com/xiaoxi-3-/如果對您有幫助,請關注我的同名簡書:
https://www.jianshu.com/u/da1677475c27本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。