importsmtplibfrom email.mime.text importMIMETextfrom email.mime.image importMIMEImagefrom email.mime.application importMIMEApplicationfrom email.mime.multipart importMIMEMultipartclassSendEMail(object):"""封装发送邮件类"""
def __init__(self, host, port, msg_from, pwd):
self.msg_frommsg_from
self.passwordpwd#邮箱服务器地址和端口
self.smtp_s smtplib.SMTP_SSL(hosthost, portport)#发送方邮箱账号和授权码
self.smtp_s.login(usermsg_from, passwordpwd)def send_text(self, to_user, content, subject, content_typeplain):"""发送文本邮件
:param to_user: 对方邮箱
:param content: 邮件正文
:param subject: 邮件主题
:param content_type: 内容格式plain or html
:return:"""msg MIMEText(content, _subtypecontent_type, _charset"utf8")
msg["From"] self.msg_from
msg["To"] to_user
msg["subject"] subject
self.smtp_s.send_message(msg, from_addrself.msg_from, to_addrsto_user)def send_file(self, to_user, content, subject, reports_path, filename, content_typeplain):"""发送带文件的邮件
:param to_user: 对方邮箱
:param content: 邮件正文
:param subject: 邮件主题
:param reports_path: 文件路径
:param filename: 邮件中显示的文件名称
:param content_type: 内容格式"""file_content open(reports_path, "rb").read()
msgMIMEMultipart()
text_msg MIMEText(content, _subtypecontent_type, _charset"utf8")
msg.attach(text_msg)
file_msgMIMEApplication(file_content)
file_msg.add_header(content-disposition, attachment, filenamefilename)
msg.attach(file_msg)
msg["From"] self.msg_from
msg["To"] to_user
msg["subject"] subject
self.smtp_s.send_message(msg, from_addrself.msg_from, to_addrsto_user)def send_img(self, to_user, subject, content, filename, content_typehtml):发送带图片的邮件
:param to_user: 对方邮箱
:param subject: 邮件主题
:param content: 邮件正文
:param filename: 图片路径
:param content_type: 内容格式subjectsubject
msg MIMEMultipart(related)#Html正文必须包含
msg.attach(content)
msg[Subject] subject
msg[From] self.msg_from
msg[To] to_user
with open(filename,"rb") as file:
img_datafile.read()
imgMIMEImage(img_data)
img.add_header(Content-ID, imageid)
msg.attach(img)
self.smtp_s.sendmail(self.msg_from, to_user, msg.as_string())
【本文由:高防服务器ip http://www.558idc.com/gfip.html 复制请保留原URL】