import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication class Client(object): def __init__(self): self.username = 'xuzhongyiqiang@secdeer.com' self.password = 'YIqiang521..' self.ip = 'smtp.exmail.qq.com' self.port = 45 def send_email(self, body, send_part2=None, smtp_server="smtp.exmail.qq.com"): """ :param body:文件内容 :param send_part2: 附件地址 :param smtp_server: smtp地址 :return: """ # 1.发件人、授权码,收件人信息 from_addr = "xuzhongyiqiang@secdeer.com" pwd = "YIqiang521.." to_addr = "1092364772@qq.com" # 2.创建实例对象,设置主题等信息 msg = MIMEMultipart() msg["Subject"] = "清零安全日报" msg["From"] = from_addr msg["To"] = to_addr # 邮件内容(按每个部分) part1 = MIMEText(body, "html", 'utf-8') msg.attach(part1) print(part1) # send_part2 :附件地址 if send_part2: part2 = MIMEApplication(open(send_part2, 'rb').read()) part2.add_header('Content-Disposition', 'attachment', filename=send_part2) msg.attach(part2) # 3.连接smtp服务器,登录服务器并发送文本 smtp_server = smtp_server server = smtplib.SMTP(smtp_server, 25) server.login(from_addr, pwd) server.sendmail(from_addr, to_addr, msg.as_string()) # as_string()把MIMEText变成一个str server.close() def send_report_mail(self, addrs=['zhangyouqian@secdeer.com'], title='爬虫报告', text='爬虫报告', addressee='尊敬的用户', addresser='泽廘安全'): addrs.append('daien@secdeer.com') # addrs.append('lijiaming@secdeer.com') message = MIMEText(text, 'plain', 'utf-8') message['Subject'] = Header(title, 'utf-8') message['From'] = Header(addresser, 'utf-8') message['To'] = Header(addressee, 'utf-8') try: server = smtplib.SMTP_SSL(self.ip, self.port) server.login(self.username, self.password) server.sendmail(from_addr=self.username, to_addrs=addrs, msg=message.as_string()) print('邮件发送成功') except Exception as e: import traceback print('Error: %s' % e.__class__.__name__) print('Message: %s' % str(traceback.format_exc())) print('邮件发送失败') if __name__ == '__main__': s = Client() s.send_report_mail(addrs=['zhangyouqian@secdeer.com'])