接口测试基础——第3篇smtplib发送带图片的邮件

Posted 自动化测试实战

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了接口测试基础——第3篇smtplib发送带图片的邮件相关的知识,希望对你有一定的参考价值。

smtplib发送邮件最后一篇,发送带图片的邮件:


# coding: utf-8

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

mail_host = 'smtp.163.com'
receivers = ['123@qq.com','456@qq.com']
receiver = ','.join(receivers)
sender = 'warrior_meng08@163.com'
password = '授权码'

msg = MIMEMultipart('alternative')
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = '主题'

msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
    '<p><img ></p>' +
    '</body></html>', 'html', 'utf-8'))

file_path = r'C:\Users\weiming\Desktop\b.jpg'
with open(file_path, 'rb') as f:
    mm = MIMEBase('image', 'jpg', filename='b.jpg')
    mm.add_header('Content-Disposition', 'attachment', filename='b.jpg')
    mm.add_header('Content-ID', '<0>')
    mm.add_header('X-Attachment-Id', '0')
    mm.set_payload(f.read())
    encoders.encode_base64(mm)
    msg.attach(mm)

try:
    server = smtplib.SMTP()
   # 加上这句就可以打印出所有的log,更方便我们定位问题    server.set_debuglevel(1)    server.connect(mail_host, 25)    server.login(sender, password)    server.sendmail(sender, receiver,msg.as_string())    server.close()    print 'Success' except smtplib.SMTPException:    print 'Error'