使用可变数量的变量在Python中发送电子邮件

时间:2016-02-21 22:34:09

标签: python html string variables dynamic

假设:

today_ids = ['id1', 'id2', 'id5']
base_line_ids = ['id1','id2','id3','id4']

added_ids = set(today_ids).difference(base_line_ids)
removed_ids = set(base_line_ids).difference(today_ids)

if len(removed_ids):
    print('The following ids were removed:\n{}'.format('\n'.join(removed_ids)))
else:
    print('No ids removed')

if len(added_ids):
    print('The following ids were added:\n{}'.format('\n'.join(added_ids)))
else:
    print('No ids added')

...并添加一些额外的处理,我最终会得到:

  • 对于任何给定的执行,removed_ids的列表,可能为空,也可能为空。
  • zip个已添加的id-href对,每次都可能为空,也可能不为空。

我现在需要构建一个HTML电子邮件模板,考虑到/或/两个列表可能已填充或为空。以下是一种可能排列的示例模板:其中删除了一个ID,另外两个添加了

  html = """\
    <html>
      <head></head>
      <body>
        <h2>The following changes have been made to the main page:</h2>
           <h3> Instruction IDs Added</h3>
           <a href=link_to_url_of_instruction_id_X>Instruction ID #X</a>
           <a href=link_to_url_of_instruction_id_Y>Instruction ID #Y</a>
           <h3> Instruction IDs Removed</h3>
           <a href=link_to_url_of_instruction_id_A>Instruction ID #A</a>
        </p>
      </body>

</html>

我认为尝试动态创建模板本身将是一种过度的(也许是可能的),即只添加删除的指令ID&#34;如果实际有一个被删除。我决心插入文字“没有”#39;在这种情况下(如果没有ID 添加)。

我知道str.format()string.Template可用于在事先知道变量数量时插入变量值。但是,当变量的数量可以变化时,我们如何动态插入

1 个答案:

答案 0 :(得分:1)

使用Jinja2等模板语言,您可以使用以下模板:

<html>
  <head></head>
  <body>
    <h2>The following changes have been made to the main page:</h2>
      <h3> Instruction IDs Added</h3>
      {% for instruction_id in added_instruction_ids %}
        <a href="{{instruction_id.url}}">Instruction ID #{{instruction_id.id}}</a>
      {% endfor %}
      <h3> Instruction IDs Removed</h3>
      {% for instruction_id in removed_instruction_ids %}
        <a href="{{instruction_id.url}}">Instruction ID #{{instruction_id.id}}</a>
      {% endfor %}
    </p>
  </body>
</html>

您甚至可以使用if语句来实现“动态模板”请求:

<html>
  <head></head>
  <body>
    <h2>The following changes have been made to the main page:</h2>
      {% if len(added_instruction_ids) %}
      <h3> Instruction IDs Added</h3>
      {% endif %}
      {% for instruction_id in added_instruction_ids %}
        <a href="{{instruction_id.url}}">Instruction ID #{{instruction_id.id}}</a>
      {% endfor %}
      {% if len(removed_instruction_ids) %}
      <h3> Instruction IDs Removed</h3>
      {% endif %}
      {% for instruction_id in removed_instruction_ids %}
        <a href="{{instruction_id.url}}">Instruction ID #{{instruction_id.id}}</a>
      {% endfor %}
    </p>
  </body>
</html>

注意:上面的示例假定以下数据传递给模板引擎:

{
  added_instruction_ids: [
    {
      id: X,
      url: link_to_url_of_instruction_id_X
    }, {
      id: Y,
      url: link_to_url_of_instruction_id_Y
    }
  ],
  removed_instruction_ids: [
    {
      id: A,
      url: link_to_url_of_instruction_id_A
    }
  ]
}