码迷,mamicode.com
首页 > 编程语言 > 详细

python之发送邮件~

时间:2018-07-08 00:29:19      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:管理   span   odi   name   style   plain   报告   测试   模块   

 

在之前的工作中,测试web界面产生的报告是自动使用python中发送邮件模块实现,在全部自动化测试完成之后,把报告自动发送给相关人员

 

其实在python中很好实现,一个是smtplib和mail俩个模块来实现,主要如下:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import os

sender = ‘lounq10000@126.com‘
receives = ‘86043473@qq.com‘
cc_receiver = ‘70907583@qq.com‘
subject = ‘Python auto test‘

msg = MIMEMultipart()
msg[‘From‘] = sender
msg[‘To‘] = receives
msg[‘Cc‘] = cc_receiver
msg[‘Subject‘] = subject
msg.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‘,‘yangych@824029‘)
sendmail.sendmail(sender,receives,msg.as_string())
sendmail.quit()

 

在这里我们可以把发送mail的代码进行封装成一个函数供外部调用,如下:


import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import os

def sendMail(subject,textContent,sendFileName):
sender = ‘lounq10000@126.com‘
receives = ‘86043473@qq.com‘
cc_receiver = ‘70907583@qq.com‘
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‘,‘yangych@824029‘)
sendmail.sendmail(sender,receives,msg.as_string())
sendmail.quit()

 

这里把主题、正文和附件文件作为参数代入,函数中的其他变量也可以作为参数输入,个人觉得没什么必要,但可以把其他的一些变量放到文件来读取,这样方便管理

 

python之发送邮件~

标签:管理   span   odi   name   style   plain   报告   测试   模块   

原文地址:https://www.cnblogs.com/watertaro/p/9278906.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!