在之前的工作中,测试web界面产生的报告是自动使用python中发送邮件模块实现,在全部自动化测试完成之后,把报告自动发送给相关人员
其实在python中很好实现,一个是smtplib和mail俩个模块来实现,主要如下:
import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBaseimport os sender = ‘[email protected]‘receives = ‘[email protected]‘cc_receiver = ‘[email protected]‘subject = ‘Python auto test‘ msg = MIMEMultipart()msg[‘From‘] = sendermsg[‘To‘] = receivesmsg[‘Cc‘] = cc_receivermsg[‘Subject‘] = subjectmsg.attach(MIMEText(‘Dont reply‘,‘plain‘,‘utf-8‘)) os.chdir(‘H:\\‘)with open(‘auto_report03.html‘,‘r‘,encoding = ‘utf-8‘) as fp: att = MIMEBase(‘html‘,‘html‘) att.add_header(‘Content-Disposion‘,‘attachment‘,filename = ‘auto_report03.html‘) att.set_payload(fp.read()) msg.attach(att) sendmail = smtplib.SMTP()sendmail.connect(‘smtp.126.com‘,25)sendmail.login(‘lounq10000‘,‘[email protected]‘)sendmail.sendmail(sender,receives,msg.as_string())sendmail.quit()
在这里我们可以把发送mail的代码进行封装成一个函数供外部调用,如下:
import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBaseimport os def sendMail(subject,textContent,sendFileName): sender = ‘[email protected]‘ receives = ‘[email protected]‘ cc_receiver = ‘[email protected]‘ subject = subject msg = MIMEMultipart() msg[‘From‘] = sender msg[‘To‘] = receives msg[‘Cc‘] = cc_receiver msg[‘Subject‘] = subject msg.attach(MIMEText(textContent,‘plain‘,‘utf-8‘)) os.chdir(‘H:\\‘) with open(sendFileName,‘r‘,encoding = ‘utf-8‘) as fp: att = MIMEBase(‘html‘,‘html‘) att.add_header(‘Content-Disposion‘,‘attachment‘,filename = sendFileName) att.set_payload(fp.read()) msg.attach(att) sendmail = smtplib.SMTP() sendmail.connect(‘smtp.126.com‘,25) sendmail.login(‘lounq10000‘,‘[email protected]‘) sendmail.sendmail(sender,receives,msg.as_string()) sendmail.quit()
这里把主题、正文和附件文件作为参数代入,函数中的其他变量也可以作为参数输入,个人觉得没什么必要,但可以把其他的一些变量放到文件来读取,这样方便管理
原文地址:https://www.cnblogs.com/watertaro/p/9278906.html
时间: 2024-10-08 01:38:44