import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
class SendEMail(object):
"""封装发送邮件类"""
def __init__(self, host: str, port: int, user: str, pwd: str):
self.host = host
self.port = port
self.user = user
self.pwd = pwd
def __send(self, msg):
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(self.host, self.port)
smtpObj.login(self.user, self.pwd)
smtpObj.sendmail(self.user, msg["To"], msg.as_string())
print("邮件发送成功")
except Exception as e:
print("邮件发送失败")
def send_text(self, to_user: str, content: str, subject: str):
"""
发送文本邮件
:param to_user: 对方邮箱
:param content: 邮件正文,文本格式
:param subject: 邮件主题
:return:
"""
# 使用email构造邮件
msg = MIMEText(content, _subtype='plain', _charset="utf8")
msg["From"] = self.user
msg["To"] = to_user
msg["subject"] = subject
self.__send(msg)
def send_html(self, to_user: str, content: str, subject: str):
"""
发送html格式邮件
:param to_user: 对方邮箱
:param content: 邮件正文,html格式
:param subject: 邮件主题
:return:
"""
# 使用email构造邮件
msg = MIMEText(content, _subtype='html', _charset="utf8")
msg["From"] = self.user
msg["To"] = to_user
msg["subject"] = subject
self.__send(msg)
def send_attachment(self, to_user: str, content: str, subject: str, files: list):
"""
发送附件邮件
:param to_user: 对方邮箱
:param content: 邮件正文,文本格式
:param subject: 邮件主题
:return:
"""
# 创建一个带附件的实例
msg = MIMEMultipart()
msg['From'] = self.user
msg['To'] = to_user
msg['subject'] = subject
# 邮件正文内容
msg.attach(MIMEText(content, 'plain', 'utf-8'))
# 构造附件
for file in files:
att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
_, file_name = os.path.split(file)
att["Content-Disposition"] = 'attachment; filename="{}"'.format(file_name)
msg.attach(att)
self.__send(msg)