基于Python的接口自動(dòng)化測(cè)試(4)

封裝郵件發(fā)送,用于發(fā)送測(cè)試報(bào)告

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import mimetypes
import os


class SendEmail(object):

    # 創(chuàng)建SMTP對(duì)象(用途為發(fā)送郵件)
    # 連接郵件服務(wù)器
    # 登錄
    # 發(fā)送郵件請(qǐng)求(郵件內(nèi)容通過(guò)email模塊構(gòu)造郵件)
    # 退出

    def __init__(self, host="smtp.163.com", user="jj_wu1991@163.com", pwd="XXXXXX"):

        self.mail_host = host #服務(wù)器
        self.user_sender = user #用戶(hù)名
        self.pwd = pwd #密碼

    def send(self, receivers, subject, content, msg_type="html", attachment=[]):

        msg = MIMEMultipart()
        msg["To"] = receivers
        msg["Subject"] = Header(subject, "utf-8")

        # 正文
        msg.attach(MIMEText(content, msg_type, "utf-8"))

        # 添加附件
        for address in attachment:
            with open(address, "rb") as f:
                ctype, encoding = mimetypes.guess_type(address)
                if ctype is None or encoding is not None:
                    ctype = 'application/octet-stream'
                maintype, subtype = ctype.split('/', 1)

                mime = MIMEBase(maintype, subtype, filename=os.path.basename(address))
                mime.add_header('Content-Disposition', 'attachment', filename=os.path.basename(address))
                # mime.add_header('Content-ID', '<0>')
                # mime.add_header('X-Attachment-Id', '0')
                mime.set_payload(f.read())
                encoders.encode_base64(mime)
                msg.attach(mime)

        try:
            smtpObj = smtplib.SMTP()
            # smtpObj.set_debuglevel(1)
            smtpObj.connect(self.mail_host)
            smtpObj.login(self.user_sender, self.pwd)
            smtpObj.sendmail(self.user_sender, receivers.split(","), msg.as_string())
            smtpObj.quit()
            print "郵件發(fā)送成功"
        except smtplib.SMTPException as e:
            print "Error:發(fā)送郵件失敗"
            print e.args[0], e.args[1]


if __name__ == '__main__':

    sendemail = SendEmail()
    sendemail.send("jj_wu1991@163.com", "標(biāo)題", "測(cè)試測(cè)試",
                   attachment=["C:/Users/Administrator/Pictures/1.jpg"])


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容