#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : pythonProject
# File : sendmail.py
# @Time : 2022/4/2 22:40
# @Author : lilu
"""
1,导包
2,建立连接
3、身份认证
4.发送邮件
5、邮件内容:发送人,接收人,主题,内容
"""
import smtplib
from email.mime.multipart import MIMEMultipart # 发送邮件
from email.mime.text import MIMEText # 邮件内容
from email.mime.image import MIMEImage # 发送图片
from test_api.common.readconf import readconf
from email.header import Header
from test_api.common.log import *
def sendmail():
# 设置smtplib所需要的参数
# 服务器地址
email_info = readconf('email_info')
smtp_server = email_info["smtp_server"]
# 发送人邮件账户密码
username = email_info["sender"]
password = email_info["password"]
# 发送人
sender = email_info["sender"]
# 一个收件人
# recipient = email_info["to_mail"]
# 多个收件人
recipients = email_info["to_mail"]
# 抄送人
# cc_mail = email_info["cc_mail"]
# 发送主题
subject = email_info["subject"]
subject = Header(subject, 'utf-8').encode()
# 构造邮件对象MIMEMultipart对象
# 下面的主题,发件人,收件人日期显示在邮件页面上
em = MIMEMultipart()
em["subject"] = subject
em["From"] = sender
em["To"] = recipients
# # em["Cc"] = cc_mail
# # em["Date"] = '2022-4-3'
# 构造文字内容
text = "python 自动化接口测试报告" # 正文内容
text_plain = MIMEText(text, 'plain', 'utf-8')
em.attach(text_plain)
# 构造图片链接
send_img_file = open(r'D:\pythonProject\img\OIP-C.jpg', 'rb').read()
image = MIMEImage(send_img_file)
image.add_header('Content-ID', '<image1>')
image["Content-Disposition"] = "attachment;filename='OIP-C.jpg'"
em.attach(image)
# 构造html
# 发送正文中的图片:由于包含未被许可的信息,网易邮箱定义为垃圾邮件,
# 报554 DT:SPM :<p><img src="cid:image1"></p>
# html = """
# <html>
# <head></head>
# <body>
# <p>Hi!<br>
# How are you?<br>
# Here is the <a href="https://www.cnblogs.com/du-hong/">link 自动化接口测试报告</a> you wanted.<br>
# </p>
# </body>
# </html>
# """
# text_html = MIMEText(html, 'html', 'utf-8')
# text_html["Content-Disposition"] = "attachment;filename='texthtml.html'"
# em.attach(text_html)
# 构造附件
send_file = open(r'D:\pythonProject\test_api\report\report.html', 'rb').read()
text_att = MIMEText(send_file, 'base64', 'utf-8')
text_att["Content-Type"] = "application/octet-stream"
text_att.add_header('Content-Disposition', 'attachment', filename='report.html')
em.attach(text_att)
# 连接服务器 发送邮件
try:
smtp = smtplib.SMTP()
smtp.connect(smtp_server)
# smtp.set_debuglevel(1) # 可以打印出和SMTP服务器交互的所有信息。
smtp.login(username, password)
smtp.sendmail(sender, recipients, em.as_string())
file_and_console('邮件发送成功')
except Exception as e:
file_and_console(f'邮件发送失败{e}')
finally:
smtp.quit()
![]()