1. 程式人生 > 實用技巧 >如何用Python傳送電子郵件(含附件)

如何用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 = '[email protected]'
mail_pass = 'xxxxxx'
mail_from = 'rainbird'
mail_to   = '[email protected]'
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 = '[email protected]'
mail_pass = 'xxxxxx'
mail_from = 'rainbird'
mail_to   = '[email protected]'
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

需要原始碼的 點選這裡獲取原始碼