Python-SMTP發送郵件(HTML、圖片、附件)

來源:互聯網
上載者:User

標籤:控制   自動化測試   zhang   login   read   fir   ftime   firefox   點贊   

前言:

SMTP(Simple Mail Transfer Protocol)即簡易郵件傳輸通訊協定,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。

一、Python發送HTML郵件
# -*- coding: utf-8 -*-# @Time    : 2018/6/6 上午11:27# @Author  : Wang# @File    : test_mail_html.pyimport smtplibfrom email.header import Headerfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextdef 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_reportmsg.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)

以上~~對你有協助的話,點贊吧~??

Python-SMTP發送郵件(HTML、圖片、附件)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.