Create Draft Outlook Email with table using Python

This post uses Python to query a table from SQL Server, attach the table into the email body and create a draft Outlook email. Below is the code and my Youtube video will explain the steps.

The Python code:

import win32com.client as win32
import pandas as pd
import numpy as np
import pyodbc
from datetime import datetime
import logging


# Connect to datebase to get data

def ConnectToSql():
    try:
        global conn
        conn =\
        (
            pyodbc.connect(driver = '{SQL Server};', Server =  'LAPTOP-D423RSYUN\SQLSERVER2019;', database = 'SgStats;',
                                        uid = 'sa;', pwd = 'your_password;')
        )
        cursor = conn.cursor()
        print('Connection successful')
        
    except Exception as Argument:
        now = datetime.now()
        f = open('Log.txt', 'a')
        f.write('\n' + str(now) + '\n' + str(Argument))
        f.close()
        print('Connection to db not successful')


ConnectToSql()


# Query SQL to dataframe

labour_force_query = 'SELECT * FROM M182331_LabourForce WHERE (Year = 2022 OR Year = 2021)'
labour_force_df = pd.read_sql(labour_force_query, conn)
labour_force_df
df_html = labour_force_df.to_html(index = False)


# Create a draft Outlook mail

def CreateDraftEmail(send_to, send_cc, subject, email_body):

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = send_to
    mail.Cc = send_cc
    mail.Subject = subject
    mail.HtmlBody = email_body
   
    mail.save()


config_file_path = r"C:\Users\your_folder\Documents\Create Draft Outlook Email\Config File.xlsx"




# Initializing variables

email_df = pd.read_excel(config_file_path, sheet_name = 'Email_Settings')
email_list = email_df.values.tolist()
print(email_list)
 
for item in email_list:
    send_to = item[0]
    send_cc = item[1]
    subject = item[2]
    email_body = item[3]

    email_body = email_body.replace("<Table>", df_html)
    CreateDraftEmail(send_to, send_cc, subject, email_body)


The 2 Outlook draft emails created with the table: