【Robotframework】腳本跑完後自動發送郵件

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
import email.MIMEMultipart
from email.header import Header
import os
import mimetypes

def send_email(file_names=[]):
    # 第三方 SMTP 服務
    receivers= ['602860910@qq.com']
    test_result=0
    print receivers
    mail_host="smtp.qq.com"  #設置服務器
    mail_user="602860910@qq.com"    #用戶名
    mail_pass="jnqatqlyepmpbcgi"   #口令,QQ郵箱是輸入受權碼,在qq郵箱設置 裏用驗證過的手機發送短信得到,不含空格
    sender = '6028601910@qq.com'

    #設置郵件中的測試結果
    resultstr = '失敗' if test_result else '經過'

    main_msg = email.MIMEMultipart.MIMEMultipart()
    message = MIMEText('''附件是本次自動化構建的報告,請注意查收 \n\n''', 'plain', 'utf-8')
    main_msg.attach(message)
    result = MIMEText('測試結果: '+resultstr, 'plain', 'utf-8')
    main_msg.attach(result)
    ## 讀入文件內容並格式化
    for file_name in file_names:
        data = open(file_name, 'rb')
        ctype,encoding = mimetypes.guess_type(file_name)
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream'
        maintype,subtype = ctype.split('/',1)
        file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
        file_msg.set_payload(data.read())
        data.close()
        email.Encoders.encode_base64(file_msg)#把附件編碼

        basename = os.path.basename(file_name)
        file_msg.add_header('Content-Disposition','attachment', filename = basename)#修改郵件頭
        main_msg.attach(file_msg)

    main_msg['From'] = Header("robot自動發送", 'utf-8')
    reciverstr = ';'.join(receivers)
    main_msg['To'] = Header(reciverstr, 'utf-8')

    subject = 'robotframework測試結果'
    main_msg['Subject'] = Header(subject, 'utf-8')


    try:
        smtpObj = smtplib.SMTP_SSL()
        smtpObj.connect(mail_host, 465)
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(sender, receivers, main_msg.as_string())
        print "郵件發送成功。"
    except smtplib.SMTPException, e:
        print "Error: 沒法發送郵件。錯誤緣由:", e
send_email(file_names=['E:\\pics\\1.png','E:\\pics\\2.jpg'])
相關文章
相關標籤/搜索