python代码实现邮件发送
python实现邮件自动发送,同时可以带上附件,并向多人发送邮件
#coding:utf-8
import smtplib,os
from tools.configData import configKV
from email.mime.text import MIMEText
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
class mail(object):
"""
host:指定连接的邮箱服务器,port:端口,user:邮箱用户名,password:邮箱密码,sender:邮件发送者地址,receiver:邮件接收者地址,msg:邮件内容
"""
def sendmail(self, host, port, user, password, sender, receiver, msg):
smtp = smtplib.SMTP()
smtp.connect(host, port)
smtp.login(user, password)
smtp.sendmail(sender, receiver, msg)
smtp.quit()
def get_Msgs(self): #邮件body内容
config=configKV()
url=config.getKeys('url.ini','url')
host_port=config.getKeys_values('hostport.ini','host_port')
msgs = 'xxxx系统/xxxx接口全量测试报告' + '\n' \
'1.概述' + '\n' \
'测试目的:全量stockid验证行情接口的正确性' + '\n' \
'被测接口:'+str(url)+ '\n' \
'2.测试环境' + '\n' \
'服务器IP:xxx.xxx.xxx.xxx' + '\n' \
'服务器端口:8088'+ '\n' \
'3.数据库信息' + '\n' \
'数据库ip:xxx.xxx.xxx.xxx'+ '\n' \
'数据库用户名:8080' + '\n' \
'数据库密码:abcabc'+ '\n' \
'4.测试方式' + '\n' \
'自动测试' + '\n' \
'5.风险点'+'\n'\
'1)测试是否通过是与公共接口(xxx.xxx.xxx.xxx)比较确定的,可能存在公共接口和测试接口数据都不正确的情况'+'\n' \
'2)测试用例更新不及时'+ '\n' \
'3)测试环境出现异常' + '\n' \
'4)其他未能预测的风险' + '\n' \
"注:测试数据详见附件!缺陷可能会很多,故不再写入excel,可sql语句查询(SELECT * FROM mms.full_result t WHERE t.result='0';)"
return msgs
#emailName:邮件名称,msgs:邮件body
#host:指定连接的邮箱服务器,port:端口,user:邮箱用户名,password:邮箱密码,sender:邮件发送者地址,receiver:邮件接收者地址,多个接收者则可以组织成一个list
def sendReport(self,msgs,emailName,host, port, user, password, sender, receiver):
xlsxpart = MIMEApplication(open('xxx/xxx/report.xlsx','rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename=report.xlsx) #加入要发送的附件
msg = MIMEMultipart()
msg.attach(xlsxpart)
msg.attach(MIMEText(msgs, 'plain', 'utf-8'))
msg['Subject'] = Header(emailName, 'utf-8').encode()
self.sendmail(host,port,user,password,sender,receiver, msg.as_string())