简体   繁体   中英

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

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.

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. ie (<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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM