Araz Mohammadnejad
Araz Mohammadnejad

Reputation: 41

Table Format in email body using Python Exchangelib library

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 = '[email protected]'
    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='[email protected]')])

    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

Upvotes: 0

Views: 4355

Answers (1)

Erik Cederstrand
Erik Cederstrand

Reputation: 10220

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

Upvotes: 2

Related Questions