如何用Python发送电子邮件(含附件)

电子邮件自诞生到现在,依旧是重要的通讯工具.在日常工作大量的告警,自动化报表依旧是通过邮件来完成.以前一直是只发送html正文,前两天遇到了发附件的情况,顺道解决了邮件名乱码的问题,记录一下

正常发送邮件

电子邮件到今天这个时间点,处理垃圾邮件的管控,很多云服务商和电子邮件服务商已经不再支持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)

结语

发邮件并不是什么困难的事儿,只是邮件涉及一堆参数,主机地址,用户名,密码啥的,把这些东西放在配置项里是好习惯.

 

此文转载文,著作权归作者所有,如有侵权联系小编删除!

原文地址:https://www.tuicool.com/articles/yuu6Z3a

 

需要源码的 点击这里获取源码

 

posted @ 2020-10-05 13:56  湘九  阅读(599)  评论(0编辑  收藏  举报