接口测试基础——第2篇smtplib发送带附件的邮件

我先给大家补充一个用QQ发送纯文本电子邮件的代码,用QQ的朋友可以参考一下:

# coding=utf-8  
import smtplib
from email.mime.text import MIMEText
mail_host = “smtp.qq.com”
receivers = “123@qq.com”
sender = “456@qq.com”
passwd = ‘QQ邮箱的授权码’
contents = “python发送邮件”
# 构造邮件正文
msg=MIMEText(contents,”plain”,”utf-8”)
# 构造邮件头部
msg[“From”]=sender
msg[“To”]=receivers
msg[“Subject”] = “主题”
try:
server = smtplib.SMTP_SSL(mail_host, 465)
server.login(sender, passwd)
server.sendmail(sender, receivers, msg.as_string())
print “发送成功”
except smtplib.SMTPException:
print “无法发送”

今天我们要写的代码是发送带附件的电子邮件:

 


# coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
sender = '你的邮箱@163.com'
passwd = '授权码'
receivers = ['123@qq.com','456@qq.com']
receiver = ','.join(receivers)
mail_host = 'smtp.163.com'
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = 'Python test'
# 邮件正文
msg.attach(MIMEText('sending email test', 'plain', 'utf-8'))
# 构造附件1
att1 = MIMEText(open('文件的路径比如:C:\\Users\\lenovo\\Desktop\\a.txt', 'rb').read(), 'base64', 'utf-8')
att1['Content-Type'] = 'application/octet-stream'
att1['Content-Disposition'] = 'attachment; filename= "a.txt"' msg.attach(att1)
# 构造附件
att2 = MIMEText(open('文件的路径比如:C:\\Users\\lenovo\\Desktop\\b.txt').read(), 'base64', 'utf-8')
att2['Content-Type'] = 'application/octet-stream'
att2['Content-Disposition'] = 'attachment; filename="b.txt"' msg.attach(att2)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(sender, passwd)
smtpObj.sendmail(sender, receiver, msg.as_string())
print 'Success'
except smtplib.SMTPException:
print 'Error'

运行以后就可以收到带有附件的电子邮件了。

如果不明白,就多谢两遍

 

微信公众号搜索“自动化测试实战”或扫描下方二维码添加关注~~~

posted @ 2017-10-17 15:47  孟船长  阅读(2573)  评论(0编辑  收藏  举报