作為數(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
和往常一樣,我們必須先導(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
[ report1 ]是您的sub-confiq。filename,dialect并且query是子配置的屬性。
您可以使用以下代碼讀取配置文件。
FOLDER = path.dirname(path.realpath(__file__))
CONFIG_FILE = path.join(FOLDER, "query_detail.conf")
config = configparser.RawConfigParser()
config.read(CONFIG_FILE)
編寫(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)
此自定義功能將讀取您傳入的子配置文件的屬性,并輸出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