SendEmail.py 2.52 KB
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import smtplib  
from email.mime.multipart import MIMEMultipart  
from email.header import Header  
from email.mime.text import MIMEText  
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from commons.Logging import log

def send_email_text():
    # 1. 编写邮件内容(Email邮件需要专门的MIME格式)
    msg = MIMEText('this is a test email', 'plain', 'utf-8')  
    
    # 2. 组装Email头(发件人,收件人,主题)
    msg['From'] = 'autotest@diligrp.com'  # 发件人
    msg['To'] = 'lixi@diligrp.com'  # 收件人
    msg['Subject'] = 'Api Test Report'  # 邮件主题
    
    # 3. 连接smtp服务器并发送邮件
    smtp = smtplib.SMTP_SSL('smtp.exmail.qq.com')  
    smtp.login('autotest@diligrp.com', 'MvkuGGCfMtAdbJvE') 
    smtp.sendmail("autotest@diligrp.com", "lixi@diligrp.com", msg.as_string())
    smtp.quit()


def send_email(send_file,send_to=["lixi@diligrp.com"],cc_to=["lixi@diligrp.com"]):
    
    log_path=os.path.dirname(os.path.dirname(__file__))
    log_path=log_path+"/report/test.log"
    send_msg=(",".join(str(i) for i in send_to))
    cc_msg = (",".join(str(j) for j in cc_to))
    msg = MIMEMultipart()  # 混合MIME格式
    msg['From'] = 'autotest@diligrp.com'  # 发件人
    msg['To'] = send_msg  # 收件人
    msg['cc'] = cc_msg  # 抄送人
    msg['Subject'] = Header('接口测试报告', 'utf-8')  # 中文邮件主题,指定utf-8编码
    
    text = MIMEText('this is a test email', 'plain', 'utf-8')
    msg.attach(MIMEText(open(send_file,'rb' ).read(), 'html', 'utf-8'))  

    att1 = MIMEText(open(send_file, 'rb').read(), 'base64', 'utf-8') 
    att1["Content-Disposition"] = 'attachment; filename="report.html"'  
    
    att2 = MIMEText(open(log_path, 'rb').read(), 'base64', 'utf-8')  
    att2["Content-Type"] = 'application/octet-stream'
    att2["Content-Disposition"] = 'attachment; filename="test.log"' 
    msg.attach(text)
    msg.attach(att1)
    msg.attach(att2)

    #一下发送日志不会在test.log上,因为提前msg.attach了
    log.info("发送邮件")
    try:
        smtp = smtplib.SMTP_SSL('smtp.exmail.qq.com')  # smtp服务器地址 使用SSL模式
        re=smtp.login('autotest@diligrp.com', 'MvkuGGCfMtAdbJvE')  # 用户名和密码
        smtp.sendmail("autotest@diligrp.com", send_to+cc_to, msg.as_string())
        print(re)
    except Exception as e:
        log.error(str(e))
        print(e)
    finally:
        smtp.quit()
        log.info("邮件发送完毕")