使用SQL结果作为附件,在Python中安排每月的电子邮件



我想在Microsoft SQL Server Management Studio中查询数据库>将查询保存为XLSX文档>把文档保存在我的电脑上>每个月将相同的文档作为附件发送给另一个用户。我已经到了生成电子邮件的地步,但我还没有找到多少关于如何安排这一点的指导。

下面的代码:

import pyodbc
import pandas as pd
import win32com.client as client
import pathlib
conn = pyodbc.connect('Driver={SQL Server};'
'Server=[ServerID];'
'Database=[Name of Database];'
'Trusted_Connection=yes;')
cursor = conn.cursor()
#Insert SQL query
sql_query = pd.read_sql_query('''[MY SQL QUERY]''',conn)

#write to new workbook given file path and new document name
writer = pd.ExcelWriter(r'DirectoryFilename.xlsx', engine='xlsxwriter')
# define the new workbook and sheet to place data on
sql_query.to_excel(writer, startrow = 0, sheet_name='Sheet1', 
index=False)
#Indicate workbook and worksheet for formatting
workbook = writer.book
worksheet = writer.sheets['Sheet1']
#Update row width to fit text
for i, col in enumerate(sql_query.columns):
# find length of column i
column_len = sql_query[col].astype(str).str.len().max()
# Setting the length if the column header is larger
# than the max column value length
column_len = max(column_len, len(col)) + 2
# set the column length
worksheet.set_column(i, i, column_len)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
excel_path = pathlib.Path(r'DirectoryFilename.xlsx')
str(excel_path.absolute())
excel_absolute = str(excel_path.absolute())
outlook = client.Dispatch("Outlook.Application")
#0 represents new mail items
message = outlook.CreateItem(0)
message.Display()
message.To = "myemailaddress@outlook.com"
message.CC = "managersemailaddress@outlook.com"
message.Subject = "Automated Report"
message.body = "Hello - Please see attached report which includes all data you requested. This will be provided to you on a monthly basis."
message.Attachments.Add(excel_absolute)

你应该使用Windows 10调度程序,它将根据你的配置运行代码。

点击这里阅读更多。

最新更新