简体   繁体   English

如何将 CSS 添加到我使用 Python 通过电子邮件发送的 HTML 文件中

[英]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.这工作正常,并使用 html 发送邮件,但是,我没有收到我申请的 CSS。 Any idea how to fix that?知道如何解决吗?

The name of the CSS file is style.css. CSS 文件的名称是 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.您正在尝试使用格式化的 HTML 发送电子邮件,如果您在 stackoverflow 上搜索它,您会得到一些结果,告诉您很少支持外部 CSS 样式表。 This means that the "style.css" file will not be sent with your e-mail in any way.这意味着“style.css”文件不会以任何方式随您的电子邮件一起发送。

The solution to your problem is to create a custom html template with inline style CSS added to your html.您的问题的解决方案是创建一个自定义 html 模板,并将内联样式 CSS 添加到您的 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.即(<div style="color:blue;background:pink;font-size:16px;font-weight:bold;>蓝色 16px 大小的粉红色背景上的粗体文本)并在电子邮件中发送。

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.请注意,并非所有 CSS 都支持电子邮件 - 我不会链接到列出所有 HTML 和 CSS 支持的页面,但您可以轻松找到多个资源来帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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