(五十一)自动化测试高级应用之自动发邮件功能-发送带附件的邮件

随笔记录方便自己和同路人查阅。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  学习selenium自动化之前,最好先学习HTML、CSS、JavaScript等知识,有助于理解定位及操作元素的原理。关于python和selenium安装请自行搜索别的资料,这里就不多做介绍了,所有例子均使用python3.6+selenium执行的。

#------------------------------------------------我是可耻的分割线-------------------------------------------

发送带附件的邮件

在发送文件时,有时需要发送附件,下面的实例实现了带附件的邮件发送。

# !/usr/bin/env python
# -*- coding: UTF-8 –*-
__author__ = 'Mr.Li'
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

#发送邮箱服务器
smtpserver = 'smtp.qq.com'
#发送邮箱
sender = '[email protected]'
#接收邮箱
receiver = '[email protected]'
#发送邮箱用户/密码
user = '[email protected]'
password = 'mbnzfxlnmwbkbcfb'#这里不能填写邮箱密码而是填写邮箱授权码
#发送邮件主题
subject = 'Python send email test'

#发送的附件
sendfile = open("d:\\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.attach(att)

#链接发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msgRoot.as_string())
smtp.quit()

相比于上一个实例,通过MIMEMultipart()模块构造的带附件的邮件如下图:

猜你喜欢

转载自www.cnblogs.com/lirongyang/p/11595851.html