Python+selenium 邮件自动发送(3)

邮件自动发送–发送带附件的邮件

想法:在测试的过程中,发送邮件的时候除了发送正文和标题之外,还需要发送图片或者文件想要的附件

思路:python提供了smtplib发送邮件的库,email构造邮件的库,既可以发送正文,也可以发送附件,用到的具体的包是:
from email.mime.multipart import MIMEMultipart

构造附件的方法如下:
#读取到D:1.txt的文件的所有内容,然后装载到定义的变量att中
send_file=open(r’D:\1.txt’,‘rb’).read()
att=MIMEText(send_file,‘base64’,‘utf-8’)
att[‘Content-Type’]=‘application/octet-stream’
att[‘Content-Disposition’]=‘attachment;filename=“1.txt”’

完整的发送邮件带附件的代码如下:

#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from  email.mime.multipart import MIMEMultipart

smtpserver='smtp.163.com'
user='summerXXX@163.com'
password=''

sender='summerXXX@163.com'
receive='XXX@qq.com'

content='<html><body><h3>自动化测试报告正文</h3></body></html>'
subject='selenium 自动化测试'

#构造附件
send_file=open(r'D:\1.txt','rb').read()
att=MIMEText(send_file,'base64','utf-8')
att['Content-Type']='application/octet-stream'
att['Content-Disposition']='attachment;filename="1.txt"'

#构造邮件内容
magRoot=MIMEMultipart()
magRoot.attach(MIMEText(content,'html','utf-8'))
magRoot['Subject']=subject
magRoot['From']=sender
magRoot['To']=receive
magRoot.attach(att)

#发送邮件
smtp=smtplib.SMTP_SSL(smtpserver,465)

#给服务器发送请求
smtp.helo(smtpserver)
smtp.ehlo(smtpserver)

smtp.login('summerXXX@163.com','  ')
print "开始发送邮件"
smtp.sendmail(sender,receive,magRoot.as_string())
print "邮件发送完成"
smtp.quit()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值