import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
class configEmailToSMTP:
"""
发送邮件及附件
"""
def __init__(self, title, content, receivers):
"""
:param title: 邮件主题
:param content: 邮件内容
:param enclosure: 附件的文件
:param receivers: 收件人邮箱
"""
self.__mail_host = "host.xxxx.com"
self.__mail_user = "xxx@xxx.com"
self.__mail_pass = ''
self.__sender = 'xxx@xxx.com'
self.title = title
self.content = content
# self.enclosure = enclosure
self.receivers = receivers
# self.filename=filename
def get_to(self, cc=None):
"""
:param cc: 传入抄送人
:return:
"""
message = MIMEMultipart()
message['Subject'] = self.title
message['From'] = self.__sender
message['to'] = self.receivers
if cc is not None:
message['Cc'] = cc
# 邮件正文内容:
message.attach(MIMEText(self.content, 'plain', 'utf-8'))
# 添加附件
# if self.enclosure!=None:
# with open(self.enclosure, "r", encoding='utf-8') as f:
# content = f.read()
#
# part1 = MIMEText(content, 'html'",utf-8")
# part1.add_header("Content-Disposition", "attachment", filename=('gbk', '', self.filename + ".html"))
# message.attach(part1)
self.get_to_run(message, cc)
def get_to_run(self, message, cc):
"""
try except;链接并发送
:param message: 接收要发送的信息
:param cc: 接收抄送人
:return:
"""
try:
# if sys.platform=='linux':
# print('在服务器上发送邮件,使用SMTP_SSL')
# smtp_obj = smtplib.SMTP_SSL()
# smtp_obj.connect(self.__mail_host,465)
# else:
smtp_obj = smtplib.SMTP()
smtp_obj.connect(self.__mail_host, 25)
# 登录到服务器
# smtp_obj.login(self.__mail_user, self.__mail_pass)
# 发送
if cc is not None:
smtp_obj.sendmail(
message['From'], self.receivers.split(",") + cc.split(","), message.as_string())
else:
smtp_obj.sendmail(
message['From'], self.receivers.split(","), message.as_string())
# 退出
smtp_obj.quit()
print('success')
except smtplib.SMTPException as e:
print('error', e)
if __name__ == '__main__':
# 测试时,1min收到
configEmailToSMTP("自动化测试发送邮件是否正常", '自动化测试报告已生成',
"xxx@xxx.com").get_to(
"xxx@xxx.com")
【0基础学测开,请添加QQ群: 833077481】
【测开交流,请添加QQ群: 677233980】
|