發送mailhtml
# -*- coding: utf-8-*- import smtplib import datetime from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from Application.Utils.Log import Log class SendMail(object): def __init__(self, recv, parameter, ssl=True, email_host='smtp.163.com', port=25, ssl_port=465): ''' :param username: 用戶名 :param passwd: 密碼 :param recv: 收件人,多個要傳list ['a@qq.com','b@qq.com] :param title: 郵件標題 :param content: 郵件正文 :param file: 附件路徑,若是不在當前目錄下,要寫絕對路徑,默認沒有附件 :param ssl: 是否安全連接,默認爲普通 :param email_host: smtp服務器地址,默認爲163服務器 :param port: 非安全連接端口,默認爲25 :param ssl_port: 安全連接端口,默認爲465 ''' self.username = '13172678133@163.com' # 用戶名 self.passwd = 'qq13172678133' # 密碼 self.recv = recv # 收件人,多個要傳list ['a@qq.com','b@qq.com] self.title = f'時間統計:{datetime.datetime.now()}' # 郵件標題 self.content = f'時間統計:{datetime.datetime.now()}' # 郵件正文 self.email_host = email_host # smtp服務器地址 self.port = port # 普通端口 self.ssl = ssl # 是否安全連接 self.ssl_port = ssl_port # 安全連接端口 self.parameter = parameter # 要發送的數據 self.mail_msg() def mail_msg(self): mail_msg = """ <table border="1"> <tr> <th>111111</th> <th>22222</th> <th>333333</th> </tr> {table} </table> """ s = """ """ for i in self.parameter: s += ''' <tr> <td>{queue_name}</th> <td>{recently_time}</th> <td>{query_number}</th> </tr> '''.format(queue_name=i.get('queue_name'), recently_time=i.get('recently_time'), query_number=i.get('query_number')) self.send_mail(mail_msg.format(table=s)) def send_mail(self, mail_msg): msg = MIMEMultipart() msg.attach(MIMEText(mail_msg, 'html', 'utf-8')) # 郵件正文的內容 msg['Subject'] = self.title # 郵件主題 msg['From'] = self.username # 發送者帳號 msg['To'] = ','.join(self.recv) # 接收者帳號列表 if self.ssl: self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port) else: self.smtp = smtplib.SMTP(self.email_host, port=self.port) # 發送郵件服務器的對象 self.smtp.login(self.username, self.passwd) try: self.smtp.sendmail(self.username, self.recv, msg.as_string()) except Exception as e: Log('Mail').info(e) self.smtp.quit()