python发送邮件封装
# encoding=utf-8
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class EmailMange:
def send_email(self, report_name):
# 1. 定义SMTP服务器
smtpserver = "smtp.163.com"
# 2. 发送邮箱的用户名和客户端密码
username = 'a1476088673@163.com'
password = "QMZYQLUFXZLXOKPZ" # 授权码
# 接收邮件邮箱
receiver = "1476088673@qq.com"
# 创建邮件对象
message = MIMEMultipart("related") # 带附件的邮件对象
# 设置邮件标题
subject = "邮件标题" # 邮件主题
# 邮件附件
fujian = MIMEText(open(report_name.name, "rb").read(), "html", "utf-8") # 附件
# 把邮件的信息组装到邮箱对象里面
message["form"] = username
message["to"] = receiver
message["subject"] = subject
message.attach(fujian)
# 登录smtp服务器并发送邮件
smtp = smtplib.SMTP() # 创建对象
smtp.connect(smtpserver) # 连接服务器
smtp.login(username, password) # 登录
smtp.sendmail(username, receiver, message.as_string()) # message.as_string()转换成字符串
smtp.quit() # 退出
if __name__ == '__main__':
EmailMange().send_email()
调用
# encoding=utf-8
import unittest
from HTMLTestRunner import HTMLTestRunner
import time
from pytestpro.emailll import EmailMange
class AAA(unittest.TestCase):
def test_01_coco(self):
print("一个笑趴菜")
if __name__ == '__main__':
# print(path)
suit = unittest.defaultTestLoader.discover("/", "*.py")
files = open("../report.html", "wb")
runner = HTMLTestRunner(stream=files, title="测试", description="报告")
runner.run(suit)
files.close() # 再发送前一定要把文件流关闭
# 发送邮件
time.sleep(3)
EmailMange().send_email(files)
标签:__,name,python,smtp,发送,import,message,邮件
From: https://www.cnblogs.com/kh-1314/p/16875669.html