Search code examples
pythonpandasemailmime

Attach CSV to email in Python without the CSV


I've seen a number of solutions about sending a CSV as an attachment in an email via Python.

In my case, my Python code needs to extract data from a Snowflake view and send it to a user group as a CSV attachment. While I know how I can do it using to_csv out of a Pandas dataframe, my question is: Do I have to create the CSV file externally at all? Can I simply run the Pandas DF through MIMEText? If so, what file name do I use in the header?


Solution

  • You don't have to create a temporary CSV file on disk, but you also can't just "attach a dataframe" since it'd have no specified on-wire format. Use a BytesIO to have Pandas serialize the CSV to memory:

    df = pd.DataFrame(...)
    bio = io.BytesIO()
    df.to_csv(bio, mode="wb", ...)
    bio.seek(0)  # rewind the in-memory file
    
    # use the file object wherever a file object is supported
    # or extract the binary data with `bio.getvalue()`