使用Python發(fā)送帶有附件的電子郵件

作為數(shù)據(jù)分析師,我通常會(huì)收到諸如“您可以每周向我發(fā)送此報(bào)告嗎?”或“您是否可以每月通過(guò)電子郵件向我發(fā)送此數(shù)據(jù)?”這樣的請(qǐng)求。發(fā)送報(bào)告很容易,但是如果您每周必須做同樣的事情,那將很煩人。這就是為什么您應(yīng)該學(xué)習(xí)如何使用python發(fā)送電子郵件/報(bào)告以及在服務(wù)器上安排腳本的原因。

在本文上,我將向您展示如何從Google BigQuery提取數(shù)據(jù)并將其作為報(bào)告發(fā)送。如果您只想知道如何使用Python發(fā)送電子郵件,則可以跳到“ 電子郵件”部分。

導(dǎo)入庫(kù)

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

from datetime import datetime
from os import path, remove
import configparser
import pandas as pd
import shutil

email-with-python1.py

和往常一樣,我們必須先導(dǎo)入庫(kù),然后再進(jìn)入編碼部分。我們將使用SMTP協(xié)議客戶(hù)端發(fā)送電子郵件。ConfigParser用于讀取存儲(chǔ)SQL查詢(xún)的配置文件。我將在下一部分中詳細(xì)解釋。

從BigQuery提取數(shù)據(jù)

首先,您必須創(chuàng)建一個(gè)配置文件來(lái)存儲(chǔ)所有SQL查詢(xún)。用SQL查詢(xún)分隔python腳本是一個(gè)好習(xí)慣,特別是當(dāng)您的SQL查詢(xún)很長(zhǎng)(超過(guò)20行)時(shí)。這樣,長(zhǎng)時(shí)間的SQL查詢(xún)不會(huì)使您的主腳本混亂。

配置文件示例

[report1]
filename : Report1
dialect : standard
query :  SELECT * FROM table1

[report2]
filename : Report2
dialect : standard
query :  SELECT * FROM table2

[report3]
filename : Report3
dialect : standard
query :  SELECT * FROM table3

email-with-python.conf

[ report1 ]是您的sub-confiq。filenamedialect并且query是子配置的屬性。

您可以使用以下代碼讀取配置文件。

FOLDER = path.dirname(path.realpath(__file__))
CONFIG_FILE = path.join(FOLDER, "query_detail.conf")
config = configparser.RawConfigParser()
config.read(CONFIG_FILE)

email-with-python2.py

編寫(xiě)函數(shù)以讀取子配置的屬性

def bigquery_to_csv(sub_conf):
    """
    Output a csv file by reading query in config file
    Arguments:
        sub_conf {String} -- [Sub Confiq name in the confiq file]
    """
    query = config.get(sub_conf, 'query')
    filename = config.get(sub_conf, 'filename')
    dialect = config.get(sub_conf, 'dialect')

    table = pd.read_gbq(query, project_id="yourProjectID", dialect=dialect, private_key="credential.json")

    filename = filename + current_date.strftime("%Y%m%d") + ".csv"
    filelist.append(filename)
    table.to_csv(filename)

email-with-python3.py

此自定義功能將讀取您傳入的子配置文件的屬性,并輸出CSV文件。

yourProjectID將是您的BigQuery項(xiàng)目ID,而credential.json將是您的BigQuery憑據(jù)JSON文件。如果您希望使用Web Auth登錄,可以將其刪除。

current_date = datetime.now()
filelist = []

# Read all the sub confiq and output csv files
sub_conf_list = config.sections()
for sub_conf in sub_conf_list:
    bigquery_to_csv(sub_conf)

print("Reports are extracted successfully!")

現(xiàn)在,您只需要循環(huán)就可以提取您在配置文件中定義的所有文件。config.sections()將在您的配置文件中返回一個(gè)子配置文件列表。

通過(guò)電子郵件發(fā)送報(bào)告和附件

定義您的電子郵件內(nèi)容

msg = MIMEMultipart()
fromaddr = 'yourEmail@outlook.com'
msg['From'] = fromaddr
msg["To"] = "sender1@outlook.com,sender2@outlook.com"
msg["Cc"] = "yourEmail@outlook.com"
msg['Subject'] = "Report"

htmlEmail = """
<p> Dear Sir/Madam, <br/><br/>
    Please find the attached Report below.<br/><br/>
<br/></p>
<p> Please contact XXX directly if you have any questions. <br/>
    Thank you! <br/><br/>
    Best Regards, <br/>
    XXX </p>
<br/><br/>
<font color="red">Please do not reply to this email as it is auto-generated. </font>
"""

for f in filelist:
    f = path.join(FOLDER, f)
    with open(f, "rb") as attached_file:
            part = MIMEApplication(
                attached_file.read(),
                Name=path.basename(f)
            )
        # After the file is closed
    part['Content-Disposition'] = 'attachment; filename="%s"' % path.basename(f)
    msg.attach(part)

上面是您定義電子郵件屬性的方式,例如發(fā)件人,收件人,抄送和主題。該htmlEmail會(huì)是你的電子郵件正文。您可以使用純文本或html作為電子郵件正文。我更喜歡使用html,因?yàn)槲铱梢赃M(jìn)行更多的格式設(shè)置,如粗體,斜體和更改字體顏色。

同樣,我們將使用循環(huán)附加所有文件。

發(fā)送郵件

msg.attach(MIMEText(htmlEmail, 'html'))
server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login(fromaddr, "yourpassword")
text = msg.as_string()
server.sendmail(fromaddr, ['sender1@outlook.com','sender2@outlook.com'], text)
server.quit()

print("Email are sent successfully!")

出于演示目的,密碼在腳本內(nèi)進(jìn)行了硬編碼。這不是一個(gè)好習(xí)慣。您應(yīng)該將密碼保存在其他文件中,以提高安全性。

現(xiàn)在,您已經(jīng)了解了如何使用Python發(fā)送帶有附件的電子郵件。

您可以在我的[Github]中(https://github.com/chingjunetao/google-service-with-python/tree/master/email-with-python)查看完整的腳本。

翻譯自:https://towardsdatascience.com/how-to-send-email-with-attachments-by-using-python-41a9d1a3860b

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Django 官方文檔 發(fā)送email 官網(wǎng)地址:[https://docs.djangoproject.com/...
    學(xué)以致用123閱讀 2,405評(píng)論 0 2
  • 一、Python簡(jiǎn)介和環(huán)境搭建以及pip的安裝 4課時(shí)實(shí)驗(yàn)課主要內(nèi)容 【Python簡(jiǎn)介】: Python 是一個(gè)...
    _小老虎_閱讀 6,338評(píng)論 0 10
  • 過(guò)年啦! 點(diǎn)擊圖片,長(zhǎng)按保存,設(shè)為壁紙。 歡迎轉(zhuǎn)發(fā)鏈接給朋友,像素?zé)o損。 設(shè)置壁紙時(shí),可以手動(dòng)調(diào)整一下圖片,以匹配...
    大鳥(niǎo)8wo閱讀 385評(píng)論 2 5
  • 今天我的固定工作時(shí)間只安排了三個(gè)小時(shí),因?yàn)楹芏嗍虑槎际恰肮Ψ蛟谠?shī)外”。 線(xiàn)上平臺(tái)的搭建正在按照計(jì)劃進(jìn)行,品牌的申請(qǐng)...
    羅洪綺閱讀 182評(píng)論 1 1
  • 把今天的時(shí)間留給我們 您并不一定感知 五月的的綠色還會(huì)再深些 我踩著樹(shù)木的蔭影 呼吸著丁香的芳香 心慢慢的徜徉 這...
    淡然li閱讀 482評(píng)論 9 14

友情鏈接更多精彩內(nèi)容