CloudXli 2020-04-10
SMTP
(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。SMTP
访问163邮箱
举例子
客户端授权码
,记下来就可以了,后面会用到[EMAIL] on_off = on # 邮件主题 subject = 接口自动化测试报告 #发送邮件信息 mail_host = smtp.163.com mail_user = 发送人邮箱@163.com # 163邮箱授权密码 mail_pass = 密码或授权密码 # 发送人 sender = 发送人@163.com # 接收人 receivers = 接收人@qq.com
import os import configparser import getPathInfo path = getPathInfo.get_Path() # 调用实例化 config_path = os.path.join(path, ‘config.ini‘) # 在path路径下再加一级,即绝对路径\config.ini config = configparser.ConfigParser() # 调用外部的读取配置文件的方法,实例化config config.read(config_path, encoding=‘utf-8‘) class ReadConfig(): def get_http(self, name): value = config.get(‘HTTP‘, name) return value def get_email(self, name): value = config.get(‘EMAIL‘, name) return value def get_mysql(self, name): value = config.get(‘DATABASE‘, name) return value
import os def get_Path(): path = os.path.split(os.path.realpath(__file__))[0] return path
import os import smtplib import time import readConfig import getPathInfo from email.mime.text import MIMEText # 发送正文 from email.mime.multipart import MIMEMultipart # 发送多个部分 from email.mime.application import MIMEApplication # 发送附件 from email.header import Header # 从email包引入Header()方法,是用来构建邮件头 read_conf = readConfig.ReadConfig() mail_host = read_conf.get_email(‘mail_host‘) # 从配置文件中读取,邮件host mail_user = read_conf.get_email(‘mail_user‘) # 从配置文件中读取,登录邮箱用户名 mail_pass = read_conf.get_email(‘mail_pass‘) # 从配置文件中读取,登录邮箱密码 subject = read_conf.get_email(‘subject‘) # 从配置文件中读取,邮件主题 sender = read_conf.get_email(‘sender‘) # 从配置文件中读取,邮件发送人 receivers = read_conf.get_email(‘receivers‘) # 从配置文件中读取,邮件收件人 mail_path = os.path.join(getPathInfo.get_Path(), ‘result‘, ‘report.html‘) # 获取测试报告路径 class TestMail(object): def send_mail(self): # 构造一个邮件体:正文、附件 msg = MIMEMultipart() # 邮件体 msg[‘From‘] = sender # 发件人 msg[‘To‘] = receivers # 收件人 tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) # 获取系统时间 msg[‘Subject‘] = Header(subject + ‘_‘ + tm, ‘utf-8‘) # 邮件主题 # 构建正文 content = """ 执行测试中…… 测试已完成!! 生成报告中…… 报告已生成…… 报告已邮件发送!! """ email_body = MIMEText(content, ‘plain‘, ‘utf-8‘) msg.attach(email_body) # 将正文添加到邮件体中 # 构建附件 att = MIMEApplication(open(mail_path, ‘rb‘).read()) # 打开附件 att.add_header("Content-Disposition", "attachment", filename=‘测试报告.html‘) # 为附件命名 msg.attach(att) # 添加附件到邮件体中 try: smtpObj = smtplib.SMTP() smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 使用smtp协议发送邮件,SSL协议来进行加密传输,465为端口号 smtpObj.login(mail_user, mail_pass) # 邮箱登录 smtpObj.sendmail(sender, receivers, msg.as_string()) # 发送邮件 print(‘send mail ok‘) smtpObj.quit() except smtplib.SMTPException: print(‘send mail fail‘) if __name__ == "__main__": send = TestMail() send.send_mail()
优化:可加上定时发送
借鉴博客: