Search code examples
pythonpandasemaildataframemime

Send Pandas DataFrame Using Python


Have seen some similar threads on here, but can't figure out how to make this work.

I want to encapsulate a Pandas dataframe into an email and send it out.. I want the table to show in the email as a table, not as an attachment

Something like this in the body of the email:

enter image description here

I tried the sample code below, but I keep getting an error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-e766c6012525> in <module>()
     31 
     32 
---> 33 msg = MIMEText(content, text_subtype)
     34 msg['Subject']=       subject
     35 msg['From']   = sender # some SMTP servers will do this automatically, not all

C:\Program Files\Anaconda3\lib\email\mime\text.py in __init__(self, _text, _subtype, _charset)
     32         if _charset is None:
     33             try:
---> 34                 _text.encode('us-ascii')
     35                 _charset = 'us-ascii'
     36             except UnicodeEncodeError:

AttributeError: 'function' object has no attribute 'encode'

Here is the code

import pandas as pd 

 Import_MICS="https://www.iso20022.org/sites/default/files/ISO10383_MIC/ISO10383_MIC.csv"
MICS=pd.read_csv(Import_MICS,sep=",")

SMTPserver = 'email-smtp.us-east-2.amazonaws.com'
sender =     'x.com'
destination = ['x.com']

USERNAME = "efsdff"
PASSWORD = "sfdfsf"

# typical values for text_subtype are plain, html, xml
text_subtype = 'html'


content="""\
Test message number 2
"""
content=MICS.to_html
subject="Sent from Python"

import sys
import os
import re

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
from email.mime.text import MIMEText


msg = MIMEText(content, text_subtype)
msg['Subject']=       subject
msg['From']   = sender # some SMTP servers will do this automatically, not all



conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.starttls
conn.login(USERNAME, PASSWORD)
conn.sendmail(sender, destination, msg.as_string())

Any ideas on how to fix would be much appreciated

Thanks!


Solution

  • content=MICS.to_html
    

    should be

    content=MICS.to_html()
    

    I also had to add encoding for the csv:

    MICS=pd.read_csv(Import_MICS,encoding = 'ISO-8859-1')