How to add CSS to the HTML file that I send through e-mail with Python

Question:

msg = MIMEMultipart('alternative')
msg['Subject'] = "Test"
msg['From'] = GMAIL
msg['To'] = EMAIL_TO_SEND_TO

html = open("template.html").read().format(Name="swix")
part2 = MIMEText(html, 'html')
msg.attach(part2)

with smtplib.SMTP("smtp.gmail.com", port=587) as connection:
        connection.starttls()
        connection.login(user=GMAIL, password=PASSWORD)
        connection.sendmail(GMAIL, EMAIL_TO_SEND_TO, msg.as_string())

This works fine and sends a mail with the html, however, I do not get the CSS that I have applied. Any idea how to fix that?

The name of the CSS file is style.css.

Asked By: Swix

||

Answers:

You are trying to send an e-mail with formatted HTML, if you search for that even here on stackoverflow you will get some results that tell you that external CSS stylesheets are rarely supported. This means that the "style.css" file will not be sent with your e-mail in any way.

The solution to your problem is to create a custom html template with inline style CSS added to your html. i.e. (<div style="color:blue;background:pink;font-size:16px;font-weight:bold;>Blue 16px Sized Bolded Text On a Pink Background) and send that in the e-mail.

Please note that not all CSS is supported for e-mails – I won’t link to pages that list all the HTML and CSS supported, but you can easily find multiple resources out there to help you out.

Answered By: Danail Gabenski

You would have to implement inline style CSS to manifest CSS in emails.
The reason is that most email providers support this style today, which means you’re likely to get the best results without running into any formatting trouble with inline style.

I’m assuming your CSS in template.html file is included in head. There’s a great API that you can simply call to transfer them into inline style HTML.
Please check this out: https://inlinestyler.visigo.com/styler/api/

Once you get the inline style HTML response from the API you can directly put them in your SMTP body.

Answered By: Dave Lee
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.