I am sending a mail by reading an excel file using pandas as dataframe. Then I am converting that dataframe using df.to_html with CSS style wrapped. Below is my code.
from email.mime.text import MIMEText
import email.message
import numpy as np
import pandas as pd
import email
import smtplib
import xlrd
filename = 'exl_sheet.xls'
df = pd.read_excel(filename)
html_string = '''
<html>
<head><title>HTML Pandas Dataframe with CSS</title></head>
<link rel="stylesheet" type="text/css" href="df_style.css"/>
<body>
{table}
</body>
</html>.
'''
df_html = html_string.format(table=df.to_html(classes='mystyle'))
sender = "sender@gmail.com"
receiver = "receiver@gmail.com"
password = 'xxxxxxxxx'
server = 'smtp.gmail.com:587'
msg = email.message.EmailMessage()
msg['Subject'] = 'Train Data'
msg['From'] = sender
msg['To'] = receiver
msg = MIMEText(df_html, 'html')
print(msg)
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(sender, password)
server.sendmail(sender, receiver, msg)
server.quit()
The output of print(msg) is:
However, the message I am receiving is as below:
That is I am not receiving the table with style. Please suggest.
First, I believe that only inline styles are supported on email -- at least that's all you can depend on across all email clients. For example, Gamil strips out all <head>
and <body>
tags. Try adding style
parameters to your HTML tags, for example:
<span style="color: red;">I am red</span>
Even if you could have external style sheets, you specified: href="df_style.css"
, which is a relative URL. If you sent that email to me, would I have that stylesheet on my PC? You would need to make it an absolute URL, such as href="http://demo.com/df_syle.css"
. Keep this in mind when you reference other items in your email, such as images.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.