一、邮件配置yaml格式
#conf.yaml mail: #发送邮件信息 smtpserver : "smtp.itcast.cn" receiver : "******@itcast.cn" username : "******@itcast.cn" password : "*******"
二、邮件配置读取
#Conf.py class ConfigYml: def __init__(self): logging.info(_config_file) #print(get_log_path()) self.r_config = YamlReader(_config_file).data self.r_db_config = YamlReader(_config_db).data def get_mail_info(self): """ 获取邮件相关设置信息 :return: """ return self.r_config["mail"]
三、邮件读取封装
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class SendMail(object): def __init__(self,username,passwd,recv,title,content, file=None, smtp_server='smtp.itcast.cn',port=25): self.username = username self.passwd = passwd self.recv = recv self.title = title self.content = content self.file = file self.smtp_server = smtp_server self.port = port def send_mail(self): msg = MIMEMultipart() #发送内容的对象 if self.file:#处理附件的 att = MIMEText(open(self.file).read()) att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"'%self.file msg.attach(att) msg.attach(MIMEText(self.content))#邮件正文的内容 msg['Subject'] = self.title # 邮件主题 msg['From'] = self.username # 发送者账号 msg['To'] = self.recv # 接收者账号列表 self.smtp = smtplib.SMTP(self.smtp_server,port=self.port)#发送邮件服务器的对象 self.smtp.login(self.username,self.passwd) try: self.smtp.sendmail(self.username,self.recv,msg.as_string()) except Exception as e: print('出错了',e) else: print('发送成功!')
四、设置run.py
def send_email(): mail_info = Conf.ConfigYml().get_mail_info() title= "接口自动化测试报告" username = mail_info["username"] passwd = mail_info["password"] receiver = mail_info["receiver"] smtp_server = mail_info["smtpserver"] content="" report_file= report_html_path+os.sep+"index.html" try: mail = SendMail( smtp_server=smtp_server, username=username, passwd=passwd, recv=receiver, title=title, content=content, file = report_file, ) mail.send_mail() except: log.error('发送邮件失败,请检查邮件配置') raise