python 给多人发送邮件,且将结果添加为附件

pythonxuexi 2019-12-07

import unittest,HTMLTestRunnerimport osdef runa():    path=os.getcwd()    print(path)    a=unittest.defaultTestLoader.discover(path,                                          pattern=‘login*.py‘)    al=unittest.TestSuite()    al.addTest(a)    #print(al)    return alimport os,timefrom email.mime.text import MIMETextfrom email.header import Headerfrom email.mime.multipart import MIMEMultipartfrom email.utils import formataddrimport smtplibdef lu(path):    filesn=os.listdir(path)    filesn.sort(key=lambda x:os.path.getmtime(path+x))    #luf=path+filesn[-1]    luf=os.path.join(path+filesn[-1])    return luf#print(lu("D:\\study\\python_api_test\\test1204\\"))def send_out(luf):    x=open(luf,‘rb‘)    email=x.read()    x.close()    usernames=‘‘    passwd=‘kclpuvarbapocagj‘ #此处密码错误,运行时,修改为正确密码    sender=‘‘    receiver=[‘‘,‘‘]    info=MIMEMultipart()    info[‘From‘]=Header("测试人:慧慧<%s>"%sender,‘utf-8‘)    info[‘To‘]=Header("请老板们查阅<%s>"%receiver,‘utf-8‘)    info[‘Subject‘]=Header(‘这是python自动化测试报告...‘,‘utf-8‘)    info.attach(MIMEText(email,‘html‘,‘utf-8‘))    attach1=MIMEText(open(luf,‘rb‘).read(),‘base64‘,‘utf-8‘)    attach1[‘Content-Type‘]=‘application/octet-stream‘    attach1["Content-Disposition"]=‘attachment;filename="result.html"‘    info.attach(attach1)    smtp=smtplib.SMTP_SSL("smtp.qq.com",465)    smtp.login(usernames,passwd)    smtp.sendmail(sender,receiver,info.as_string())    smtp.quit()    print("邮件已发出!请注意查收!")if __name__=="__main__":    #unittest.TextTestRunner().run(runa())    htmlrun=unittest.TextTestRunner()    result=os.path.join(os.getcwd()+"\\result.html") #无result.html,则会自动创建    print(result)    a=open(result,‘wb‘)    htmlrun=HTMLTestRunner.HTMLTestRunner(stream=a,                                  title=‘自动化测试结果‘,                                  description=‘具体结果如下:‘,                                          verbosity=2)    htmlrun.run(runa())    a.close()    path="D:\\study\\python_api_test\\test1204\\"    hehe=lu(path)    send_out(hehe)======================================================================小结:1.python使用了a=[‘ab‘,‘ee‘]b=‘;‘.join(a) #输出结果为ab;ee2.使用了email中的MIMEMutipart()附件att1info=MIMEMutipart()att1=MIMEText(open(‘**文件‘,‘rb‘).read(),‘base64‘,‘utf-8‘)att1=[‘Content-Type"]=‘application/octet-stream‘att1=[‘Content-Disposition‘]=‘attachment;filename="可随意命名"‘info.attach(att1)Text1=MIMEText(open(‘**文件.html‘,‘rb‘).read())info.attach(Text1,‘html‘,‘utf-8‘)
 

相关推荐