https://jingyan.baidu.com/article/647f0115b78f8d7f2148a8e8.html

1.发送HTML格式的邮件

import smtplib
from email.mime.text import MIMEText
from email.header import Header #发送邮箱服务器
smtpserver = "smtp.126.com"
#发送邮箱用户/密码
user = "发送邮箱@126.com"
password = "登陆密码"
#发送邮箱
sender = "发送邮箱@126.com"
#接收邮箱
receiver = "接收邮箱@qq.com"
#发送邮箱主题
subject = "python发送邮件"
#编写HTML类型的邮箱正文
msg=MIMEText('<html><h1>给QQ邮箱发送邮件</h1></html>','html','utf-8')
msg['Subject']=Header(subject,'utf-8')
msg['From']="张三"
msg['To']=receiver smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user,password)
try:
smtp.sendmail(sender, receiver, msg.as_string())
print("发送成功")
except smtplib.SMTPDataError as e:
print("发送失败")
finally:
smtp.quit()

2.发送文本内容的邮件

import smtplib
from email.mime.text import MIMEText
from email.header import Header msg_from = '发送邮箱@qq.com'
passwd = '授权码'
msg_to = '收件人邮箱@126.com' subject = "python邮件测试"
content = "这是我使用python smtplib及email模块发送的邮件"
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = "发送方"
msg['To'] = "接收方"
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465)
s.login(msg_from, passwd)
s.sendmail(msg_from, msg_to, msg.as_string())
print("发送成功")
except s.SMTPDataError as e:
print("发送失败")
finally:
s.quit()

其中 s = smtplib.SMTP_SSL("smtp.qq.com", 465)#相当于以下2行

s = smtplib.SMTP()

s.connect("smtp.qq.com")

3.发送带附件的邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
smtpserver = "smtp.126.com"
sender = "发送邮箱@126.com"
receiver = "接收邮箱@qq.com"
user = "发送邮箱@126.com"
password = "发送邮箱密码"
subject = "测试附件3"
sendfile = open("/Users/chenshanju/PycharmProjects/SeleniumOfJenkins/report/log.txt","rb").read() att = MIMEText(sendfile,"base64","utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] ="attachment;filename='log.txt'"
msgRoot = MIMEMultipart("related")
msgRoot["Subject"] = subject
msgRoot["From"] = sender
msgRoot["To"] = receiver
msgRoot.attach(att) smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msgRoot.as_string())
smtp.quit()

4.查找最新的测试报告

import sys,os
#获取当前脚本的目录
script_path=sys.path[0].split("/")
#获取工程的主目录
end_index=script_path.index("SeleniumOfJenkins")+1
#report所在的目录
report_dir="/".join(script_path[:end_index])+"/report"
#查看当前的文件生成列表
list_file=os.listdir(report_dir)
#对文件按照创建时间进行排序
list_file.sort(key=lambda file:os.path.getmtime(report_dir+"/"+file))
print(list_file[-1])

5.自动发送测试报告

import unittest,os,sys
from time import strftime
from HTMLTestRunner import HTMLTestRunner
import smtplib
from email.mime.text import MIMEText
from email.header import Header def get_new_report(report_dir):
"get_new_report()方法传入一个参数(测试报告所在目录),得到最新的report文件"
file_list = os.listdir(report_dir)
file_list.sort(key=lambda file:os.path.getmtime(report_dir+"/"+file))
return report_dir+"/"+file_list[-1]
def send_email(new_report):
"send_email()接收一个参数(new_report),发送邮件"
f = open(new_report,"rb")
mail_body=f.read()
f.close()
sender = "发送邮箱@126.com"
receiver = "接收邮箱@qq.com"
msg = MIMEText(mail_body,"html","utf-8")
msg['Subject'] = Header("自动化测试报告","utf-8")
msg['From'] = sender
msg['To'] = receiver
smtp = smtplib.SMTP()
smtp.connect("smtp.126.com")
smtp.login("发送邮箱@126.com","发送邮箱密码")
try:
smtp.sendmail(sender,receiver,msg.as_string())
print("发送成功")
except :
print("发送失败")
finally:
smtp.quit() if __name__=="__main__":
"""1.执行测试 2.获取最新报告 3.发送邮件"""
current_dir_list = sys.path[0].split("/")
index = current_dir_list.index("SeleniumOfJenkins") + 1
if index == len(current_dir_list):
home_dir = "/".join(current_dir_list)
else:
home_dir = "/".join(current_dir_list[:index])
report_dir = home_dir + "/" + "report"
test_dir = home_dir + "/testcase/testsearch"
discover = unittest.defaultTestLoader.discover(test_dir, pattern="test*.py")
filename="report/"+strftime("%Y_%m_%d_%H_%M_%S")+"_result.html"
fp = open(filename,"wb")
runner=HTMLTestRunner(stream=fp,title="百度搜索报告",description="用例执行情况")
runner.run(discover)
fp.close()
new_report = get_new_report(report_dir)
send_email(new_report)

FAQ:

1.qq邮箱需要开启imap和smtp权限


## 2.从126邮箱发送qq邮箱抛出异常smtplib.SMTPDataError
smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp1,C8mowABHGtEduABcQk94BA--.46414S2 1543551006,please see http://mail.163.com/help/help_spam_16.htm?ip=125.122.53.172&hostid=smtp1&time=1543551006')
解决方法:需要对msg['From']和msg['To']赋值
## 3.发送的附件不是指定的文件名,而是tcmime.*.bin类型的文件
原因:att["Content-Disposition"] ="attachment;filename='log.txt'"误写为Content-Dispostion
## 4.自动发送测试报告中,qq邮箱样式丢失,126邮箱正常

使用附件可以解决这个问题
```#python
import smtplib,os,sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def get_home_dir():

"获取最新的报告"

current_path_list=sys.path[0].split("/")

index = current_path_list.index("SeleniumOfJenkins")+1

if index == len(current_path_list):

home_path=sys.path[0]

else:

home_path="/".join(current_path_list[:index])

return home_path

def get_new_file():

"获取最新的报告"

file_list=os.listdir(report_path)

file_list.sort(key=lambda file:os.path.getmtime(report_path+file))

return file_list[-1]

def send_email():

"发送邮件"

new_file_name = get_new_file()
new_file = report_path + new_file_name
server = "smtp.126.com"
sender="发送邮箱@126.com"
receiver="接收邮箱@qq.com"
subject = "测试报告见附件3"
sendfile= open(new_file,"rb").read()
att = MIMEText(sendfile,"base64","utf-8")
att['Content-Type'] = "application/octet-stream"
att['Content-Disposition'] = "attachment;filename='%s'" % new_file_name
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot['From'] = sender
msgRoot['To'] = receiver
msgRoot.attach(att)
smtp = smtplib.SMTP()
try:
smtp.connect(server)
smtp.login("发送邮箱@126.com","发送邮箱密码")
smtp.sendmail(sender,receiver,msgRoot.as_string())
print("发送成功")
except:
print("发送失败")
finally:
smtp.quit()

if name=="main":

home_path = get_home_dir()

report_path = home_path + "/report/"

send_email()

python selenium-7自动发送邮件的更多相关文章

  1. 开源you-get项目爬虫,以及基于python+selenium的自动测试利器

    写在前面 爬虫和自动测试,对于python来说是最合适不过也是最擅长的. 开源的项目也很多,例如you-get项目https://github.com/soimort/you-get.盗链和爬虫神器. ...

  2. Python+Selenium学习--自动生成HTML测试报告

    前言 在脚本运行完成之后,除了在log.txt 文件看到运行日志外,我们更希望能生一张漂亮的测试报告来展示用例执行的结果.        HTMLTestRunner 是Python 标准库的unit ...

  3. Python+selenium整合自动发邮件功能

    主要实现的目的是:自动将测试报告以邮件的形式通知相关人员 from HTMLTestRunner import HTMLTestRunner import HTMLTestReport from em ...

  4. 批量群发,营销必备!Python代码实现自动发送邮件!

    在运维开发中,使用 Python 发送邮件是一个非常常见的应用场景.今天一起来探讨一下,GitHub 的大牛门是如何使用 Python 封装发送邮件代码的. 一般发邮件方法 SMTP是发送邮件的协议, ...

  5. Python selenium 文件自动下载 (自动下载器)

    MyGithub:https://github.com/williamzxl 最新代码已经上传到Github,以下版本为stupid版本. 由于在下载过程中需要下载不同文件,所以可以把所有类型放在Va ...

  6. python+selenium实现自动抢票

    使用说明 程序运行开始,需要输入出发地,目的地,出发时间,乘客信息,车次:乘客信息和车次可以输入多个 刚刚开始学习爬虫,selenium仅仅是解放了双手,运行效率不是很高: 程序运行时会打开chrom ...

  7. python selenium 练习 自动获取豆瓣阅读当前特价书籍 chrome 元素定位 窗口切换 元素过期

    豆瓣原创电子书每周推出数十本限时免费数目,一周免费期过后恢复原价.想着豆瓣原创书中有不少值得一看,便写了个脚本,免去一个个添加的烦恼. 使用了Windows下selenium+Python的组合,有较 ...

  8. python QQ邮箱自动发送邮件

    于初学者来讲在写发送邮件代码时常见的错误有SMTPAuthenticationError535,有点懵逼,检查用户名,密码正确就是报错, 想当年笔者也是这么过来的,现在就给大家分享一下个人经验: 一, ...

  9. python+selenium之自动生成excle,保存到指定的目录下

    进行之自动化测试,想把自动生成的excle保存到指定的目录下.网上百度的代码如下: import xlwt import time time = time.strftime ('%Y%m%d%H%M% ...

  10. 用Python自动发送邮件

    用Python自动发送邮件     最近需要在服务器上处理一些耗时比较长的任务,因此想到利用python写一个自动发送邮件的脚本,在任务执行完毕后发送邮件通知我.以下代码以163邮箱为例: 开通163 ...

随机推荐

  1. jQuery之阻止默认事件以及解除阻止

    大家都知道e.preventDefault()可以阻止默认时间,例如提交功能,但是怎么解除呢?以下参考于网络: 可以使用removeEventListener来移除.但是条件是addEventList ...

  2. avalon 路由问题

    1, 直接使用avalon的 amd加载器, 可以不需要 require.js 2, 配置baseUrl 路径, 这个一定要在 js所在的目录,  而不是jsp所在的目录,  如果js 和jsp分开 ...

  3. Python mode_w

    # 每次使用w模式打开文件, 都会清空这个文件(坑) f = open("胡辣汤",mode="w",encoding="utf-8") f ...

  4. 【Genymotion】add a new virtual device 失败

    Genymotion 新增虚拟设备(模拟器)时,由于网络原因,总是下载失败,如图: 下载失败提示“Unable to create virtual device: Connection timeout ...

  5. Skynet服务器框架(十) CentOS 防火墙设置

    引言: 今天修改了 skynet 服务器的 IP 地址(即 config 文件中的 address 和 master 两项参数,IP 与当前及其的保持一致,端口号为 2017),然后使用一个简单的客户 ...

  6. GitHub上最流行的Top 10 JavaScript项目

    统计出Github中所有项目的数量,几乎是不可能的,而明确指出哪些是最优秀的项目就更不可能了.如果说到JavaScript,曾经极富创新的项目(很可能)在一两个月后就会变得过时.落后.以防被淹没在大量 ...

  7. JMeter传递JSON数据

    步骤: 1.添加线程组.HTTP请求默认值.察看结果树等参考<JMeter实现bugfree登录接口测试>.这里不再赘述. 2.添加HTTP请求 在Body Data中写上输入的参数.参数 ...

  8. PHP文件上传大小设置

    PHP.INI配置:文件上传功能配置教程 打开php.ini配置文件中的upload_tmp_dir.upload_max_filesize.post_max_size等选项. php.ini中文件上 ...

  9. C语言中右大括号(})后是否加分(;)号问题

    在C语言中定义结构体时,右大括号后是需要加分号的,在C++中使用class关键字定义类时,右大括号后也是需要加分号的,而在定义函数时,右大括号后是不需要加分号的. 对这个问题的解释就是右花括号}能代表 ...

  10. CF1143F/1142C U2

    CF1143F/1142C U2 巧妙的思维题.注意到这里只用两个点就可以确定一根抛物线,联想到两点确定一条直线,尝试转化. \(y=x^2+bx+c\) 就可以写成 \(y-x^2=bx+c\) , ...