自动化测试执行完成后,需要自动发送测试报告。Python发送邮件可以使用smtplib标准模块,但该模块比较繁琐,推荐使用yagmail这个第三方模块,用法比较简单。
一、邮箱设置
1、在邮箱设置里打开smtp服务
2、开启邮箱授权码
并不是所有邮箱都有邮箱授权码。163邮箱授权码可以自己输入,qq邮箱授权码是随机码,新浪邮箱则没有邮箱授权码,直接通过登录密码发送邮件。
二、利用yagmail实现邮件发送
需要注意的是:
1、yagmail实际是封装了smtplib模块,来实现的邮件发送功能
2、直接下载的yagmail模块,发送中文附件时标题乱码(解决这个问题,需要修改模块源码)
实际用法如下:
1 import yagmail
2 username = '123456@qq.com' # 邮箱账号
3 passwd = 'abcdefghijklmnopq' # 授权码,有时效(一般是一年)
4 mail = yagmail.SMTP(user=username,
5 password=passwd,
6 host='smtp.qq.com',
7 smtp_ssl=True
8 ) # 果用的是QQ邮箱或者是使用安全协议的邮箱需要加上smtp_ssl=True
9 mail.send(
10 to=['123@163.com','456@163.com'], # 收件人,多个收件人,写成list
11 cc=['789@qq.com','999@qq.com'], # 抄送人,多个收件人,写成list
12 subject='发送邮件测试', # 邮件标题
13 contents='正常上课', # 邮件正文
14 attachments=[r'C:UsersDesktop est.txt',
15 r'C:UsersDesktop est.docx']# 发多个附件,放到一个list里面
17 )
18 print('发送成功')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #!/usr/bin/env python 2 # encoding: utf-8 3 4 from email.mime.text import MIMEText 5 from email.parser import Parser 6 from email.header import decode_header 7 from email.utils import parseaddr 8 from mgr.common.logger import * 9 import base64 10 import smtplib 11 import poplib 12 import time 13 import sys 14 reload(sys) 15 sys.setdefaultencoding('utf8') 16 17 poplib._MAXLINE=20480 18 19 20 class Email(object): 21 LIST_PATH = os.path.dirname(os.path.realpath(__file__)) 22 if os.path.exists(os.path.join(LIST_PATH, 'email.html')): 23 os.remove(os.path.join(LIST_PATH, 'email.html')) 24 25 def __init__(self, popHost='10.186.1.34', smtpHost='10.186.1.34', port=535, userName='admin@edr.com', 26 passWord='Sangfor123', bossMail='admin@edr.com'): 27 """ 28 邮箱登陆 29 :param popHost: 30 :param smtpHost: 31 :param port: 32 :param userName: 33 :param passWord: 34 :param bossMail: 35 """ 36 self.popHost = popHost 37 self.smtpHost = smtpHost 38 self.port = port 39 self.userName = userName 40 self.passWord = passWord 41 self.bossMail = bossMail 42 self.mailLink = None 43 self.mail_box = None 44 self.login() 45 #self.configMailBox() 46 47 # 登录邮箱 48 def login(self): 49 try: 50 #self.mailLink = poplib.POP3_SSL(self.popHost) 51 self.mailLink = poplib.POP3(self.popHost) 52 LOG_DEBUG("POP3连接成功:%s" % self.mailLink) 53 self.mailLink.set_debuglevel(0) 54 self.mailLink.user(self.userName) 55 self.mailLink.pass_(self.passWord) 56 self.mailLink.list() 57 LOG_DEBUG(u'login success!') 58 except Exception as e: 59 LOG_DEBUG(u'login fail! ' + str(e)) 60 quit() 61 62 def delete_email(self, option="all"): 63 """ 64 清空邮箱邮件 65 :param option: all 删除所有邮件 66 :return: 67 """ 68 ret = False 69 LOG_DEBUG("初始化:删除邮箱all邮件") 70 mail_list = self.mailLink.list()[1] 71 number = len(mail_list) 72 LOG_DEBUG("当前一共有%r封邮件" % number) 73 74 if option == "all" and number != 0: 75 for i in range(number, 0, -1): 76 LOG_DEBUG("正在删除第%r封邮件......" % i) 77 self.mailLink.dele(i) 78 79 mail_list = self.mailLink.list()[1] 80 if len(mail_list) == 0: 81 LOG_DEBUG("邮件删除完成") 82 ret = True 83 84 return ret 85 86 # 获取邮件 87 def retrmail(self, recv="admin@edr.com", send="EDR终端检测响应平台<admin@edr.com>", 88 e_subject="平台状态告警", send_time=time.strftime('%d %H:%M:%S'), 89 mark=str(time.strftime('%H-%M-%S')), email_path=""): 90 """ 91 92 :param recv: 收件人邮箱 93 :param send: 发送人邮箱 94 :param e_subject: 主题 95 :param send_time: 发送时间 96 :param mark: 邮件标签 97 :param email_path:下载邮件存在路径 98 :return: 99 """ 100 101 try: 102 mail_list = self.mailLink.list()[1] 103 except Exception as e: 104 LOG_ERROR("获取邮件出现异常:%s" %e) 105 return False 106 else: 107 if len(mail_list) == 0: 108 LOG_DEBUG("当前没有邮件") 109 return False 110 111 numbers = len(mail_list) 112 113 for number in range(numbers, 0, -1): 114 """取最新的一封邮件""" 115 # resp, lines, octets = self.mailLink.retr(number) 116 mail = self.mailLink.retr(number)[1] 117 118 msg_content = b' '.join(mail).decode('utf-8', 'ignore') # 将邮件组合到一起,生成邮件信息 119 msg_content = Parser().parsestr(msg_content) 120 121 #self.mailLink.dele(number) 122 subject = u'' 123 sender_platform = u'' 124 senter_add = u'' 125 message = u'' 126 try: 127 for i in range(0, len(mail)): 128 if mail[i].startswith('Subject'): 129 subject = mail[i][9:].split('?b')[1] 130 if mail[i].startswith('From'): 131 sender_platform = mail[i][10:].split('b?')[1].split('=')[0] 132 senter_add = mail[i]