I have written a simple script that logs into my company's SQL Server, executes a query, uses pandas to read the results into a variable, then calls the .to_csv function and finally attaches that file to an outlook email (using win32com.client) to send off to a specified end user(s).
Currently the script works, but when I call .to_csv, I have to specify a file location, save the file to that location, then reference that file path when creating the outlook attachment. I'm looking to eliminate that step by creating the .csv and attaching to an email without physically saving the file somewhere. Is this possible?
Here is some sample code of what I have:
import pyodbc
import pandas as pd
import os
from datetime import date
import win32com.client as win32
cnxn_str = () #cnxn string detail)
cnxn = pyodbc.connect(cnxn_str)
query = '''
#QUERY GOES HERE
'''
data = pd.read_sql(query, cnxn)
del cnxn
path = (file path) **<-- this is what I want to eliminate**
data.to_csv(os.path.join(path,f'{date.today()}_data.csv'),encoding='utf-8',index=False)** <-- can I call .to_csv without a path?
**
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = ''#recipient
mail.Subject = ''
mail.Body = 'Hey Matthew, attached is a current Open Orders query.'
# To attach a file to the email (optional):
attachment = os.path.join(path,f'{date.today()}_data.csv') **<-- how can I create .csv and attach to email in one step without saving the file somewhere?**
mail.Attachments.Add(attachment)
mail.Send()
No, not in Outlook Object Model -
Attachments.Addtakes either a fully qualified file name or another Outlook item. The native Outlook API (Extended MAPI) knowns nothing about files (it works withIStreamCOM interface for the attachment data), but to use it you'd need either C++ or Delphi or a MAPI wrapper like Redemption (I am its author).