0

I am exploring in python to write email using library with body content which contains a table content.

I have tried the code to add table in the body content.

    import pandas as pd
    import numpy as np
    from exchangelib import Account, Credentials, Message, Mailbox
    dfReport = pd.read_excel("test.xlsx")
    FilteredData = dfReport[dfReport["ColumnID"].str.contains('MyCharacter')]
    DataTable = pd.pivot_table(FilteredData ,index="Processor",values="TicketID",aggfunc=np.count_nonzero,margins=True)

    EmailAdd = 'XXX@YYY.Z'
    EmailPass = 'XXXXXX'
    MyAccount = Account(EmailAdd,credentials=Credentials(EmailAdd,EmailPass),autodiscover=True)

    MyMessage = Message(account=MyAccount, folder=MyAccount.sent,subject='Daily motivation', body=DataTable, to_recipients=[Mailbox(email_address='AAA@BBB.CC')])

    MyMessage.send_and_save()

below demonstration is expected in message body:

    Name    Count
    Item 1  53
    Item 2  38
    Item 3  123
    Item 4  175
    Item 5  212

but in outlook exchange email looks like this:

    Name
    Count
    Item 1         53
    Item 2                38
    Item 3     123
    Item 4    175
    Item 4            212

1 Answers1

2

To properly control the format of your email body, you need to send the body as HTML.

The easiest is probably to convert the dataframe to a string, encapsulate it in <pre> tags and define a mono-spaced font.

You can read up on creating emails with an HTML body at https://github.com/ecederstrand/exchangelib#creating-updating-deleting-sending-and-moving

Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
  • I tried your advise and it was worked for manually typed table by HTML Codes. can you guide me how can I changed extracted `DataTable` from `"test.xlsx"` to HTML code ? – Araz Mohammadnejad Aug 27 '19 at 11:40
  • here is the manually written table code: `body=HTMLBody('
    FirstnameLastname Age
    JillSmith 50
    EveJackson 94
    ')`
    – Araz Mohammadnejad Aug 27 '19 at 11:40
  • Pandas apparently has a `.to_html()` method you can use: https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_html.html – Erik Cederstrand Aug 27 '19 at 19:28
  • Thanks for you valuable support. I used `DataHtml = pd.DataFrame.to_html(DataTable )` for changing table data into html code then use it `body = HTMLBody(DataHtml)` for exchange body – Araz Mohammadnejad Aug 30 '19 at 11:25