利用Python编程,批量发送电子邮件(含附件)
电子邮件自诞生到现在,依旧是重要的通讯工具.在日常工作大量的告警,自动化报表依旧是通过邮件来完成.以前一直是只发送html正文,前两天遇到了发附件的情况,顺道解决了邮件名乱码的问题,记录一下
正常发送邮件
很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:961562169
电子邮件到今天这个时间点,处理垃圾邮件的管控,很多云服务商和电子邮件服务商已经不再支持smtp通过25端口来发送,而要使用ssl加密的465端口
本文演示基本腾讯企业邮箱,估计QQ个人邮箱也一样.
Python:3.8.2
#!/usr/local/bin/python3.8.2 # -*- coding: utf-8 -*- import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText mail_host = "smtp.exmail.qq.com" mail_user = "xxx@xxx.xx" mail_pass = "xxxxxx" mail_from = "rainbird" mail_to = "xxx@xxx.xx" mail_title= "rainbird"s mac book" me = mail_from +"<"+mail_user+">" mail_body = "/result_report.html" msg = MIMEText(mail_body,_subtype="html",_charset="utf8") msg["Subject"] = mail_title msg["From"] = me msg["To"] = mail_to try: s = smtplib.SMTP_SSL(host=mail_host) s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, mail_to, msg.as_string()) s.close() print("send mail success!") except Exception as e: print(e)
发送附件
这部分比较困难的部分就是邮件名乱码.经过尝试指定邮件名UTF8编码,就可以了.
#!/usr/local/bin/python3.8.2 # -*- coding: utf-8 -*- import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText mail_host = "smtp.exmail.qq.com" mail_user = "xxx@xxx.xx" mail_pass = "xxxxxx" mail_from = "rainbird" mail_to = "xxx@xxx.xx" mail_title= "rainbird"s mac book" me = mail_from +"<"+mail_user+">" def file_get_content(file_name): with open (file_name,"r") as f: return f.read() mail_body = "/result_report.html" mail_att = "/result.html" msg = MIMEMultipart() msg["Subject"] = mail_title msg["From"] = me msg["To"] = mail_to msg.attach(MIMEText(file_get_content(mail_body),_subtype="html",_charset="utf8")) # 邮件附件 att = MIMEText(file_get_content(mail_att), "base64", "utf-8") att.add_header("Content-Disposition", "attachment", filename=("utf-8", "", "report.html")) msg.attach(att) try: s = smtplib.SMTP_SSL(host=mail_host,port=465) s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, mail_to, msg.as_string()) s.close() print("send mail success!") except Exception as e: print(e)
结语
发邮件并不是什么困难的事儿,只是邮件涉及一堆参数,主机地址,用户名,密码啥的,把这些东西放在配置项里是好习惯.