htmlpython-3.xhtml-email

Python Dataframe space characters being removed when sent via email (win32)


When using Python 3, why does WIN32 mail.send alter the df.to_html values when sending an email?

The example below shows a dataframe with three test values with different spaces between the word 'TEST' and the number value.They can clearly be seen and confirmed in the print(html_table).

However, when you check the email, only a single space exists between the word 'TEST' and the number value.

I want to keep the integrity of the original dataframe and include the extra spaces.

import pandas as pd
import win32com.client as win32


# Sample DataFrame
data = {'Test': ['TEST1', 'TEST2', 'TEST3'],
        'Value': ['TEST 1', 'TEST  2', 'TEST   3'],
        'NOTES': ['ONE SPACE', 'TWO SPACES', 'THREE SPACES']}
df = pd.DataFrame(data)

# Convert DataFrame to HTML without altering spaces
html_table = df.to_html(index=False, escape=False, justify='left')

print(html_table)


outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.subject = 'Test'
mail.To = #Add in your own email address
mail.HTMLBody = """
                """ + html_table + """<br>
        </body>
        </html>
        """
mail.send

Solution

  • Have you tried this?

    import pandas as pd
    import win32com.client as win32
    
    # Sample DataFrame
    data = {'Test': ['TEST1', 'TEST2', 'TEST3'],
            'Value': ['TEST 1', 'TEST  2', 'TEST   3'],
            'NOTES': ['ONE SPACE', 'TWO SPACES', 'THREE SPACES']}
    df = pd.DataFrame(data)
    
    # Convert DataFrame to HTML, preserving spaces with CSS
    html_table = df.to_html(index=False, escape=False, justify='left')
    html_table = html_table.replace('<td>', '<td style="white-space: pre;">')
    
    print(html_table)
    
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.Subject = 'Test'
    mail.To = 'your_email@example.com'  # Replace with your email
    mail.HTMLBody = f"""
    <html>
    <body>
    {html_table}<br>
    </body>
    </html>
    """
    mail.Send()
    

    You need to apply white-space: pre;