python邮件发送封装类

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from common.config import configs

class EmaliUtils:
def __init__(self,smtp_body, attch_path =None):
self.smtp_server = 'smtp.qq.com'
self.smtp_prot = 25
self.smtp_send = '***@qq.com'
self.smtp_password = 'mkfarwmvotfqfgec'
self.smtp_receiver = configs.SMTP_RECEIVER
self.smtp_cc = '***@qq.com'
self.smtp_subject = '自动化邮件发送'
self.smtp_body = smtp_body
self.attch_path = attch_path

def email_message_body(self):
message = MIMEMultipart()
message['from'] = self.smtp_send
message['to'] = self.smtp_receiver
message['Cc'] = self.smtp_cc
message['subject'] = self.smtp_subject
message.attach(MIMEText(self.smtp_body, 'html', 'utf-8'))
# print(self.attch_path)
if self.attch_path:
attach_file_obj = MIMEText(open(self.attch_path,'rb').read(), 'base64', 'utf-8')
attach_file_obj['Content-Type'] = 'application/octet-stream'
attach_file_obj.add_header('Content-Disposition', 'atachment',
filename=('gbk', '', os.path.basename(self.attch_path)))
message.attach(attach_file_obj)
return message


def send_mail(self):
smtp = smtplib.SMTP()
smtp.connect(self.smtp_server, self.smtp_prot)
smtp.login(self.smtp_send, self.smtp_password)
smtp.sendmail(self.smtp_send, self.smtp_receiver.split(',') + self.smtp_cc.split(','),
self.email_message_body().as_string())
smtp.close()




if __name__ == '__main__':
email_u = EmaliUtils('自动化邮件发送', '../report')
email_u.send_mail()

posted on 2021-02-27 22:13  心品茗香  阅读(92)  评论(0编辑  收藏  举报

导航