Home > Enterprise >  Email pandas dataframe as csv attachment
Email pandas dataframe as csv attachment

Time:11-16

So, I have a cleaned dataframe that I'm trying to export as an attachment using Outlook. In this case, I'm using win32.client to send an email.

outlook = win32com.client.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = '[email protected]'
mail.Subject = 'Sample Email'
mail.Body = '''Please find data attached and below.\n
Hello! This is the body'''
mail.Attachments.Add(Source=df_merged.to_csv)

I'm trying to attach df as the attachment in csv or excel. I'm getting this error.

TypeError: Objects of type 'method' can not be converted to a COM VARIANT

I figured out that this only accepts a system address for the attachment and not the address of a dataframe object. Any ideas will be appreciated.

CodePudding user response:

You are passing the to_csv itself function as the parameter: mail.Attachments.Add(Source=df_merged.to_csv)

Use this instead: mail.Attachments.Add(Source=df_merged.to_csv())

You could also temporarily store the Dataframe on the disk and use the path of the file instead. You can then remove it using the os package

  • Related