【问题标题】:Write an email in HTML form containing jQuery and CSS through a Python script.通过 Python 脚本编写包含 jQuery 和 CSS 的 HTML 格式的电子邮件。
【发布时间】:2018-05-12 12:58:28
【问题描述】:

我正在尝试编写一个 python 程序,根据某些情况向我发送电子邮件。如果值符合某些条件,我希望以红色打印,否则以绿色打印。下面是我的代码的一个小sn-p。我不确定如何添加这个 jquery/Javascript 部分。

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

me = "my@email.com"
you = "you@email.com"

msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
#a=0
#if a==0:
#       color="blue"
#else:
#       color="red"
html = """
<html>
  <head>
      <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script>
                var a=0;
                 if (a<2) {
                  $("p").css("color","red");
                  }
                </script>
  </head>
  <body>
        <p>Hi!<br>
               How are you?<br>
                      Here is the <a
                      href='http://www.python.org'>link</a> you
                      wanted.
                          </p>
                            </body>
                            </html>
                            """


part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()

【问题讨论】:

  • 这段代码有什么问题?
  • 如果邮件客户端执行 JavaScript,我会感到惊讶。也许您可以在 HTML 中添加 &lt;style&gt; 部分,或者只使用内联样式?

标签: jquery python html css email


【解决方案1】:

出于明显的安全原因,电子邮件中的 JavaScript 不会(也不应该)被执行,至少在收到的电子邮件中是这样。 很快: Don't use javascript for this.

由于您使用的是 Python,我建议您使用 Jinja2 等模板引擎来创建 HTML。然后可以在发送消息之前在发送方检查条件。

例如:

from jinja2 import Environment, PackageLoader, select_autoescape

env = Environment(
    loader=PackageLoader('yourapp', 'templates'),
    autoescape=select_autoescape(['html'])
)

template = env.get_template('email.html')
data = {'message': 'Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org'}

email = template.render(data)

# Rest of code to send the email here.

这假设有一个 templates/ 文件夹来存储您的模板。在这种情况下应该有一个html文件templates/email.html

email.html 现在可以相当简单了:

<html>
<head>
<style>
  <!-- This only adds the css if the expression is true -->
  {% if some_variable_from_context > 2 %}
  p { color: red; }
  {% endif %}
</style>
</head>
<body>
  <!-- This loads the message (see the template.render(data)) -->
  {{ message }}
</body>
</html>

更简单的解决方案:

只需使用 CSS。如果条件为真,则创建一个添加您想要的样式的 CSS 类,并且仅在条件为真时将该类添加到您想要的对象。现在,您可以简单地在 Python 代码中进行条件检查,而不必依赖 jquery / javascript,这在电子邮件中可能无法正常工作。

【讨论】:

    猜你喜欢
    • 2014-01-05
    • 2014-08-30
    • 2018-02-03
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2016-12-19
    相关资源
    最近更新 更多