1

I have a HTML file which is essentially a table. However some of the cells in the table are highlighted and when I convert my HTML file to text as specified in other stackoverflow answers, the coloring of the cells and other CSS specifications disappear in the mail.

Code :

import smtplib
import csv
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

text = open("final.html", 'r').read()
message = MIMEMultipart(
    "alternative", None, [MIMEText(text), MIMEText(text,'html')])

server = smtplib.SMTP('smtp.gmail.com', 25)
server.connect("smtp.gmail.com",25)
server.ehlo()
server.starttls()
server.ehlo()
server.login('mail', "password")

server.sendmail('from_mail', 'to_mail', message.as_string())
server.quit()

Finally, the message is converted to string as in message.as_string(). I guess when the message is converted to a string, the CSS formatting options are taken away.

HTML input file :

HTML input file - image final.html file

Current output in mail: current output in mail - image

Any help would be appreciated. Thanks a lot !

Tony Stark
  • 511
  • 2
  • 15

1 Answers1

1

Firstly, most email clients don't support External CSS within the mail. This can be converted to Inline CSS with premailer.

import smtplib
import ssl
import premailer
from email.message import EmailMessage

SERVER_ADDRESS = "smtp.gmail.com"  
SERVER_PORT = 587
EMAIL_ADDRESS = 'your email'
EMAIL_PASSWORD = 'your email password'
RECIPIENT_EMAIL = 'recipient's mail'

text = open("final.html", 'r').read()
text = premailer.transform(text)

msg = EmailMessage()
msg['Subject'] = "the subject"
msg['From'] = EMAIL_ADDRESS
msg['To'] = RECIPIENT_EMAIL

msg.set_content('content')
msg.add_alternative(text, subtype='html')

# Create a SSLContext object with default settings.
context = ssl.create_default_context()

with smtplib.SMTP(SERVER_ADDRESS, SERVER_PORT) as smtp:
    smtp.ehlo()  
    smtp.starttls(context=context)  
    smtp.ehlo()
    smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
    smtp.send_message(msg)  

This github repo was helpful.

Suraj
  • 2,253
  • 3
  • 17
  • 48