接口测试基础——第2篇smtplib发送文字邮件
Posted 自动化测试实战
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了接口测试基础——第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'
运行以后就可以收到带有附件的电子邮件了。
如果不明白,就多谢两遍,如果还不明白,可以留言,船长会在看到后的第一时间给大家解答。代码都是船长运行通过的,所以遇到问题后大家可以先想一想问什么会运行不通过~~~大家和我一起加油!
以上是关于接口测试基础——第2篇smtplib发送文字邮件的主要内容,如果未能解决你的问题,请参考以下文章