#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021-10-16 9:23
# @Author : herry
# @File : SendEmail.py
# @software: PyCharm
# @describe: SendEmail
import base64
import smtplib
from email.header import Header
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class SendEmail:
'''
本方法只支持QQ邮箱的发送,
如果要适配其他的需要修改第三方 SMTP 服务地址 mail_host="smtp.XXX.com"
'''
def __init__(self, sender, recivers, secret):
'''
:param sender: 发送者
:param recivers: 接收者,List对象
:param secret: 发送者的密钥
'''
self.sender = sender
self.recivers = recivers
self.secret = secret
try:
#设置服务器地址
self.smtpObj = smtplib.SMTP("smtp.exmail.qq.com")
#采用密钥进行登录
self.smtpObj.login(sender, secret)
except Exception as e:
print(e)
print("邮件服务器登录失败")
def send_Email(self, title, mail_msg,attr=None,images=None):
"""
:param title: 标题
:param mail_msg: 邮件内容
:param attr: 附件
:param imgs: 图片地址,正文引用图片是按images1,images2。。。格式进行引用
:return:
"""
##创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header(self.sender, 'utf-8')
message['To'] = Header(", ".join(self.recivers), 'utf-8')
message['Subject'] = Header(title, 'utf-8')
###邮件正文内容
message.attach(MIMEText(mail_msg, 'html', 'utf-8'))
##如果有附件时,添加附件
if attr:
for file_str in attr:
try:
attr=MIMEText(open(file_str,"rb").read(),'base64','utf-8')
attr["Content-Type"]='application/octet-stream'
attr.add_header("Content-Disposition", "attachment", filename=("gbk", "", file_str.split("\\")[-1])) #解决附件未中文时,出现文件名不正确的情况
message.attach(attr)
except Exception as e:
print(e)
print("上传附件失败!")
#如果有图片时,添加图片
if images:
i=1;
for im_file in images:
# 指定图片为当前目录
try:
fp = open(im_file, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<images%d>' % i)
i += 1
message.attach(msgImage)
except Exception as e:
print(e)
print("读取图片数据错误~~~")
# 定义图片 ID,在 HTML 文本中引用,自动从1开始,如果是图片引用时,也是按顺序引用
try:
self.smtpObj.sendmail(sender, recivers, message.as_string())
print("发送邮件成功!")
except Exception as e:
print(e)
print("发送邮件失败~")
if __name__ == "__main__":
sender = "XXX@qq.com"
recivers = ['XXX@qq.com']
secret = "6H52BtsFXjh6ejaY"
send = SendEmail(sender, recivers, secret)
# send.send_Email_Text("python测试", "oh~~~~")
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.runoob.com">这是一个链接</a></p>
<p><img src="cid:images1"</p>
"""
# send.send_Email_LinK("python测试", mail_msg)
# mail_msg="test~~~"
attr=["C:\\test.docx"]
imges=["E:\\工作相关\\aaa.png"]
send.send_Email("自动化测试报告", mail_msg,attr=attr,images=imges)
-------------------------------------最后---------------------------------
更多软件测试相关内容请关注“软件测试道与术”公众号或扫描下方二维码