簡體   English   中英

通過Python腳本以HTML格式編寫包含jQuery和CSS的電子郵件。

[英]Write an email in HTML form containing jQuery and CSS through a Python script.

我正在嘗試編寫一個python程序,根據某些條件向我發送電子郵件。 我希望如果值符合特定條件,則將其打印為紅色,否則將其打印為綠色。 以下是我的代碼的一小段。 我不確定如何向其中添加這個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不會(也不應該)執行,至少出於明顯的安全原因,至少在收到的電子郵件中。 很快: 不要為此使用javascript。

由於您使用的是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,無論如何這在電子郵件中都無法使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM