python发送邮件
邮件发送脚本
import smtplib from email.mime.text import MIMEText from email.header import Header from email.utils import formataddr class SendMail(): def __init__(self): self.smtpserver = 'smtp.exmail.qq.com' self.sender = '' self.user = '' self.password = '' # 邮件头接收人 self.receiver = '填写所有接收人邮箱地址,逗号分隔' def send_mail(self, my_subject, alter_info): # 发生邮箱服务器 smtpserver = self.smtpserver # 发送用户和密码 user = self.user password = self.password # 发送邮箱 sender = self.sender # 接收邮箱 receiver = self.receiver # 发送邮箱主题 subject = my_subject # 编写HTML类型的邮件正文 msg = MIMEText(""" <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="2"> <thead> <th>...</th> <th>...</th> <th>...</th> </thead> <tbody> {0} </tbody> </table> </body> </html> """.format(alter_info), 'html', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') try: # 连接发送邮件 smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print("告警发送成功!") except Exception as e: print("告警发送失败!") print(e) def send_mail_ssl(self, reciver_list, subject, content, fail_content): try: msg = MIMEText(""" <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="2"> <thead> <th>...</th> <th>...</th> <th>...</th> <th>...</th> </thead> <tbody> {0} </tbody> </table> <h3></h3> <table border="2"> <thead> <tr> <td>...</td> <td>...</td> </tr> </thead> <tbody> {1} </tbody> </table> </body> </html> """.format(content, fail_content), 'html', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = Header(self.user) # msg['To'] = Header(self.receiver, charset='utf-8') msg['To'] = formataddr(('群组接收人',self.receiver)) server = smtplib.SMTP_SSL(self.smtpserver, 465) server.login(self.user, self.password) server.sendmail(self.user, reciver_list, msg.as_string()) server.quit() print("告警邮件发送成功!") except Exception as e: print("告警邮件发送失败!") print(e) if __name__ == '__main__': sendmail = SendMail() reviver_list = ["接收人测试邮箱地址"] sendmail.send_mail_ssl(reviver_list ,'邮件标题', '<tr><td>wwww</td><td>243324</td><td>4354</td></tr>', "<tr><td...</td><td>...</td></tr>")