Search code examples
pythonpyodbcpathlib

Schedule Monthly Emails in Python using SQL results as attachment


I'm looking to query a database in Microsoft SQL Server Management Studio > save the query as an xlsx document > save the document on my computer > email that same document as an attachment to another user every month. I've got to the point where I generate the email but I haven't found much guidance on how to schedule this.

Code below:

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'Directory\Filename.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'Directory\Filename.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)

Solution

  • What you should is to use Windows 10 scheduler which will run the code based on your configuration.

    Read more here.