# coding=utf-8 from email.mime.text import MIMEText from email.header import Header from smtplib import SMTP, SMTP_SSL from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.encoders import encode_base64 import traceback import os class EmailUtil(object): host_server = 'smtp.exmail.qq.com' sender_email = 'zhangbr@elab-plus.com' pwd = '306492mnA' send_name = 'elab' receiver = ['1285211525@qq.com', 'lijm@elab-plus.com', 'xuanxc@elab-plus.com'] def __init__(self): pass def send_mail(self, mail_title, content, receivers, mail_excel ): global smtp try: smtp = SMTP_SSL(self.host_server, 465) smtp.set_debuglevel(1) smtp.ehlo(self.host_server) smtp.login(self.sender_email, self.pwd) msg = MIMEMultipart('related') msg['From'] = self.send_name msg['Subject'] = Header(mail_title, 'utf-8') msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) if content: textApart = MIMEText(content) msg.attach(textApart) if mail_excel: part = MIMEBase('application', "vnd.ms-excel") with open(mail_excel, 'rb') as fp: part.set_payload(fp.read()) encode_base64(part) part.add_header('Content-Disposition', f'attachment; filename="{os.path.split(mail_excel)[1]}"') msg.attach(part) for receiver in receivers: msg['To'] = receiver try: smtp.sendmail(self.sender_email, receiver, msg.as_string()) except Exception as e: print(str(e)) smtp.sendmail(self.sender_email, receiver, msg.as_string()) print('Success!') except Exception as e: print('Error:{}'.format(str(e))) traceback.print_exc() finally: smtp.quit() dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def send_test(self): send_email = EmailUtil() send_email.send_mail('elab_test', '11', ['1285211525@qq.com'], mail_excel=r'{}/elab_mvp/resources/111.xlsx'.format(self.dir_path)) if __name__ == '__main__': send_email = EmailUtil() send_email.send_test() pass