高级电子邮件模板

2016年3月25日

电子邮件

1 min read

高级电子邮件模板

关键要点

    • SparkPost模板支持简单和高级电子邮件撰写,包括HTML、文本、条件逻辑、循环和通过替换变量的每个接收者动态数据。

    • 数组可以传递到替换数据中,允许您遍历项目(例如,文件列表、最近活动、自定义表格行)以为每个接收者生成个性化的部分。

    • 三重大括号{{{ }}}允许您插入原始的、未转义的HTML,当您的替换数据已经包含标记时,这是必需的。

    • 使用传输端点(content.attachments)时可以轻松发送附件,这将为您抽象MIME边界和编码。

    • 内联图像与附件类似,但使用cid:引用在正文中呈现。

    • 模板本身不原生支持附件,但您可以通过制作完整的RFC 5322带有MIME部分的电子邮件并将其存储为email_rfc822模板来包含它们。

    • 在构建原始RFC 5322模板时,替换仍然有效—但仅在头部和第一个HTML和文本MIME部分中。

    • 使用您编程语言的邮件客户端(例如,JavaMail)提供了另一种路径:以编程方式生成完整MIME电子邮件,并通过SparkPost传输API发送。

    • 为了可维护性,尽可能将标记和数据分开——尤其是构建包含循环或多个MIME部分的模板时。

    • 高级模板功能(条件、表达式、数组迭代)允许开发人员构建复杂的、个性化的电子邮件,而无需为每个用例重写整个模板。

Q&A 精华

  • SparkPost 模板可以处理 loops 和 arrays 吗?

    是的。模板可以使用for each构造遍历数组。这使得可以为每个收件人生成动态表格、列表或重复的HTML块。

  • 三个大括号用于什么?

    {{{ variable }}} 插入未经转义的原始 HTML。当您的替换数据已经包含 HTML 标记时,这是必需的。

  • Can I send attachments with templates?

    不能直接通过模板字段 — 但您可以通过存储包含 MIME 附件部分的email_rfc822 模板来实现。

  • 替换在RFC 5322模板中仍然有效吗?

    是的,但仅限于标头和第一个HTML +文本MIME部分内。

  • 我什么时候应该使用传输端点而不是模板?

    当发送动态附件、内嵌图片或需要SparkPost自动处理MIME时。

  • 将视图逻辑嵌入更好还是单独保持分离更好?

    最佳做法是将视图标记和数据保持分离。使用模板进行展示,并传递干净、结构化的替换数据。

  • 我可以使用编程库生成完整的MIME电子邮件吗?

    是的。像 JavaMail 这样的库允许您通过程序构建 RFC 5322 消息并通过 SparkPost 的传输 API 发送。

  • 高级模板功能是否被广泛使用?

    令人惊讶的是,很少有开发者使用它们,但它们能够解锁强大的个性化功能:循环、条件语句、内联逻辑和自定义 MIME 结构。

  • 为什么我会需要 RFC 5322 templates?

    仅在发送复杂的多部分电子邮件(附件、自定义 MIME 类型)时,SparkPost 的标准模板抽象不支持。

这篇文章是针对希望充分利用SparkPost 的电子邮件模板功能的开发人员编写的。假设您对阅读 JSON 内容和遵循基本编程流程感到舒适。当引入可能对您来说陌生的术语时,例如RFC 5322,文本将链接到其来源参考。

准备好了,我们就直接开始吧。

SparkPost 的模板传输能力使发送电子邮件变得简单。那些功能为文本HTML内容提供了抽象,这意味着大多数时候无需直接编码由RFC 5322(以前称为RFC 822)定义的原始电子邮件格式。但有时您可能希望创建更复杂的消息,这些消息具有其他多用途互联网邮件扩展(MIME)部分,这些部分并未通过 SparkPost 的 RESTful 接口直接公开。

简化 Email Composition

首先,让我们回顾一下在晴天发送电子邮件的场景。使用transmission端点提供 text 和 HTML 内容。在后台,SparkPost负责组成有效的RFC 5322电子邮件。SparkPost将从substitution_data中插入替换变量到文本和HTML内容中。这是一种为每个收件人在通用模板中生成自定义内容的强大方式。

这是一个包含HTML和文本内容以及substitution_data的transmission示例。

{
  "options": {
    "open_tracking": true,
    "click_tracking": true
  },
  "campaign_id": "christmas_campaign",
  "return_path": "bounces-christmas-campaign@domain.com",
  "metadata": {
    "user_type": "students"
  },
  "substitution_data": {
    "sender": "Big Store Team"
  },
  "recipients": [
    {
      "return_path": "123@bounces.domain.com",
      "address": {
        "email": "wilma@domain.com",
        "name": "Wilma Flintstone"
      },
      "tags": [
        "greeting",
        "prehistoric",
        "fred",
        "flintstone"
      ],
      "metadata": {
        "place": "Bedrock"
      },
      "substitution_data": {
        "customer_type": "Platinum"
      }
    }
  ],
  "content": {
    "from": {
      "name": "Fred Flintstone",
      "email": "fred@domain.com"
    },
    "subject": "Big Christmas savings!",
    "reply_to": "Christmas Sales <sales@domain.com>",
    "headers": {
      "X-Customer-Campaign-ID": "christmas_campaign"
    },
    "text": "Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{user_type}}\n {{sender}}",
    "html": "<p>Hi {{address.name}} <br>Save big this Christmas in your area {{place}}! <br>Click <a href=\"http://www.mysite.com\">here</a> and get huge discount</p><p>Hurry, this offer is only to {{user_type}}</p><p>{{sender}}</p>"
  }
}

替换数据数组

许多人意识到 SparkPost 的传输和模板端点可以在电子邮件头和电子邮件正文中进行简单的内容替换。但很多人忽略了也可以提供条件内容或可以替换的数据数组。您还可以为每个收件人提供独特的内容。在此示例中,我们向每个收件人发送一个包含独特链接的数组。

这是通过提供一个 JSON 数据数组来实现的,该数组将填充到电子邮件正文中。提供数据后,SparkPost 会在模板中使用逻辑来填充它。

在此示例中,SparkPost 将寻找名为“files_html”的替换数据,并对数组中的每个元素进行“逐个”操作。它将在“files_html”元素中创建一个具有“file”值的行。注意三重花括号包围“loop_var.file”。这是因为数组中的每个元素都包含 HTML,我们需要告知服务器按原样使用它而不转义。文本部分将是简单的文本标签和文件的 URL。

<table>
  {{each files_html}}
    <tr>
      <td>{{{loop_var.file}}}</td>
    </tr>
  {{ end }}
</table>

这是完整的工作示例:

{
  "recipients": [
    {
      "address": {
        "email": "recipient1@domain.com"
      },
      "substitution_data": {
        "files_html": [
          {
            "file": "<a href=\"http://domain.com/file1a.txt\">File 1a Description</a>"
          },
          {
            "file": "<a href=\"http://domain.com/file2a.txt\">File 2a Description</a>"
          }
        ],
        "files_plain": [
          {
            "file": "File 1a -- http://domain.com/file1a.txt"
          },
          {
            "file": "File 2a -- http://domain.com/file2a.txt"
          }
        ]
      }
    },
    {
      "address": {
        "email": "recipient2@domain.com"
      },
      "substitution_data": {
        "files_html": [
          {
            "file": "<a href=\"http://domain.com/file1b.txt\">File 1b Description</a>"
          },
          {
            "file": "<a href=\"http://domain.com/file2b.txt\">File 2b Description</a>"
          }
        ],
        "files_plain": [
          {
            "file": "File 1b -- http://domain.com/file1b.txt"
          },
          {
            "file": "File 2b -- http://domain.com/file2b.txt"
          }
        ]
      }
    }
  ],
  "return_path": "chris@test.domain.com",
  "content": {
    "from": {
      "name": "chris@test.domain.com",
      "email": "chris@test.domain.com"
    },
    "subject": "Sending with SparkPost is Fun",
    "html": "<b>Your Files:</b><br>\n<table>\n  {{each files_html}}\n    <tr><td>{{{loop_var.file}}}</td></tr>\n  {{ end }}\n</table>\n",
    "text": "Your Files:\n{{each files_plain}} {{loop_var.file}}\n{{ end }}\n"
  }
}

专业提示:在您的代码中,建议将视图标记与数据分开,但这里的目的是让示例尽可能简单易懂,所以我们创建了两个数组。一个数组用于 HTML 部分,另一个用于文本部分。在生产中使用时,通常会有一组数据,并在模板代码中编写逻辑。

许多人意识到 SparkPost 的传输和模板端点可以在电子邮件头和电子邮件正文中进行简单的内容替换。但很多人忽略了也可以提供条件内容或可以替换的数据数组。您还可以为每个收件人提供独特的内容。在此示例中,我们向每个收件人发送一个包含独特链接的数组。

这是通过提供一个 JSON 数据数组来实现的,该数组将填充到电子邮件正文中。提供数据后,SparkPost 会在模板中使用逻辑来填充它。

在此示例中,SparkPost 将寻找名为“files_html”的替换数据,并对数组中的每个元素进行“逐个”操作。它将在“files_html”元素中创建一个具有“file”值的行。注意三重花括号包围“loop_var.file”。这是因为数组中的每个元素都包含 HTML,我们需要告知服务器按原样使用它而不转义。文本部分将是简单的文本标签和文件的 URL。

<table>
  {{each files_html}}
    <tr>
      <td>{{{loop_var.file}}}</td>
    </tr>
  {{ end }}
</table>

这是完整的工作示例:

{
  "recipients": [
    {
      "address": {
        "email": "recipient1@domain.com"
      },
      "substitution_data": {
        "files_html": [
          {
            "file": "<a href=\"http://domain.com/file1a.txt\">File 1a Description</a>"
          },
          {
            "file": "<a href=\"http://domain.com/file2a.txt\">File 2a Description</a>"
          }
        ],
        "files_plain": [
          {
            "file": "File 1a -- http://domain.com/file1a.txt"
          },
          {
            "file": "File 2a -- http://domain.com/file2a.txt"
          }
        ]
      }
    },
    {
      "address": {
        "email": "recipient2@domain.com"
      },
      "substitution_data": {
        "files_html": [
          {
            "file": "<a href=\"http://domain.com/file1b.txt\">File 1b Description</a>"
          },
          {
            "file": "<a href=\"http://domain.com/file2b.txt\">File 2b Description</a>"
          }
        ],
        "files_plain": [
          {
            "file": "File 1b -- http://domain.com/file1b.txt"
          },
          {
            "file": "File 2b -- http://domain.com/file2b.txt"
          }
        ]
      }
    }
  ],
  "return_path": "chris@test.domain.com",
  "content": {
    "from": {
      "name": "chris@test.domain.com",
      "email": "chris@test.domain.com"
    },
    "subject": "Sending with SparkPost is Fun",
    "html": "<b>Your Files:</b><br>\n<table>\n  {{each files_html}}\n    <tr><td>{{{loop_var.file}}}</td></tr>\n  {{ end }}\n</table>\n",
    "text": "Your Files:\n{{each files_plain}} {{loop_var.file}}\n{{ end }}\n"
  }
}

专业提示:在您的代码中,建议将视图标记与数据分开,但这里的目的是让示例尽可能简单易懂,所以我们创建了两个数组。一个数组用于 HTML 部分,另一个用于文本部分。在生产中使用时,通常会有一组数据,并在模板代码中编写逻辑。

许多人意识到 SparkPost 的传输和模板端点可以在电子邮件头和电子邮件正文中进行简单的内容替换。但很多人忽略了也可以提供条件内容或可以替换的数据数组。您还可以为每个收件人提供独特的内容。在此示例中,我们向每个收件人发送一个包含独特链接的数组。

这是通过提供一个 JSON 数据数组来实现的,该数组将填充到电子邮件正文中。提供数据后,SparkPost 会在模板中使用逻辑来填充它。

在此示例中,SparkPost 将寻找名为“files_html”的替换数据,并对数组中的每个元素进行“逐个”操作。它将在“files_html”元素中创建一个具有“file”值的行。注意三重花括号包围“loop_var.file”。这是因为数组中的每个元素都包含 HTML,我们需要告知服务器按原样使用它而不转义。文本部分将是简单的文本标签和文件的 URL。

<table>
  {{each files_html}}
    <tr>
      <td>{{{loop_var.file}}}</td>
    </tr>
  {{ end }}
</table>

这是完整的工作示例:

{
  "recipients": [
    {
      "address": {
        "email": "recipient1@domain.com"
      },
      "substitution_data": {
        "files_html": [
          {
            "file": "<a href=\"http://domain.com/file1a.txt\">File 1a Description</a>"
          },
          {
            "file": "<a href=\"http://domain.com/file2a.txt\">File 2a Description</a>"
          }
        ],
        "files_plain": [
          {
            "file": "File 1a -- http://domain.com/file1a.txt"
          },
          {
            "file": "File 2a -- http://domain.com/file2a.txt"
          }
        ]
      }
    },
    {
      "address": {
        "email": "recipient2@domain.com"
      },
      "substitution_data": {
        "files_html": [
          {
            "file": "<a href=\"http://domain.com/file1b.txt\">File 1b Description</a>"
          },
          {
            "file": "<a href=\"http://domain.com/file2b.txt\">File 2b Description</a>"
          }
        ],
        "files_plain": [
          {
            "file": "File 1b -- http://domain.com/file1b.txt"
          },
          {
            "file": "File 2b -- http://domain.com/file2b.txt"
          }
        ]
      }
    }
  ],
  "return_path": "chris@test.domain.com",
  "content": {
    "from": {
      "name": "chris@test.domain.com",
      "email": "chris@test.domain.com"
    },
    "subject": "Sending with SparkPost is Fun",
    "html": "<b>Your Files:</b><br>\n<table>\n  {{each files_html}}\n    <tr><td>{{{loop_var.file}}}</td></tr>\n  {{ end }}\n</table>\n",
    "text": "Your Files:\n{{each files_plain}} {{loop_var.file}}\n{{ end }}\n"
  }
}

专业提示:在您的代码中,建议将视图标记与数据分开,但这里的目的是让示例尽可能简单易懂,所以我们创建了两个数组。一个数组用于 HTML 部分,另一个用于文本部分。在生产中使用时,通常会有一组数据,并在模板代码中编写逻辑。

Transmission Capabilities 中的 Attachments

传输端点还提供了发送附件的抽象。 下面您将看到附件是在 content.attachments 数组中指定的,其中数组中的每个对象描述一个单独的附件项。就像之前一样,SparkPost 将负责编码textHTMLsubstitutions 并迭代通过附件数组来编码一个格式正确的电子邮件消息。

最佳实践规定,除非显式要求作为您的服务的一部分,否则最好避免发送附件。

以下是附件所需的字段:

  • type: 附件的 MIME 类型

  • name: 附件的文件名

  • data: Base64 编码的文件数据

这就是传输内容节中附件的样子:

"content": {
  "attachments": [
    {
      "type": "audio/mp3",
      "name": "voicemail.mp3",
      "data": "TVAzIERhdGEK"
    }
  ]
}

您还可以在传输中发送“内联图像”。这些和附件非常相似,指定在 content.inline_images 数组中,其中每个 inline_image 对象与上面显示的附件对象类似。

模板中的Attachments

现在,我们已经为使用传输端点发送附件做好了适当的背景准备,让我们看看如何使用模板来执行此操作。在撰写本文时,没有像您在内联传输中找到的附件抽象。有人可能会得出结论,模板无法创建带有附件的内容。你部分正确,但有解决方法,尽管你将不再与RFC 5322格式隔离。

您可以通过亲自编码RFC 5322内容来实现模板中的附件,包括该附件。好消息是,您不会失去在电子邮件头HTML文本部分中仍然使用 替换数据 的能力。请注意,这种类型的模板将替换限制在以及第一个HTML和第一个文本部分。

以下是如何完成的示例。

RFC822 邮件

创建您的 RFC 5322 电子邮件,并包含您想要替换的数据。我在我的邮件客户端中创建了这个,并发送给自己。收到后,我复制了源代码并替换了我想动态替换的字段。

MIME-Version: 1.0
Reply-To: {{replyto}}
Subject: {{subject}}
From: {{from}}
To: {{address.email}}
Content-Type: multipart/mixed; boundary="001a113c48b0b89d92052d3051da"
--001a113c48b0b89d92052d3051da
Content-Type: multipart/alternative; boundary="001a113c48b0b89d89052d3051d8"
--001a113c48b0b89d89052d3051d8
Content-Type: text/plain; charset=UTF-8
Email with a *text attachment*.
{{body2}}
--001a113c48b0b89d89052d3051d8
Content-Type: text/html; charset=UTF-8
<div dir="ltr">
  <div>Email with a <i>text attachment</i>.</div>
  {{body1}}
<

在此消息的最后一个 MIME 部分中,您将看到 Content-Disposition: attachment; filename=myfile.txt”。这就是定义文件名的位置。您的附件内容肯定会复杂得多,但此示例试图保持简单。

Stored Template

一旦您拥有有效的 RFC 5322 邮件,就使用模板端点的email_rfc822格式来存储它,而不是使用textHTML字段。以下是此消息的content示例:

{
  "content": {
    "email_rfc822": "MIME-Version: 1.0\nReply-To: {{replyto}}\nSubject: {{subject}}\nFrom: {{from}}\nTo: {{address.email}}\nContent-Type: multipart/mixed; boundary=001a113c48b0b89d92052d3051da\n\n--001a113c48b0b89d92052d3051da\nContent-Type: multipart/alternative; boundary=001a113c48b0b89d89052d3051d8\n\n--001a113c48b0b89d89052d3051d8\nContent-Type: text/plain; charset=UTF-8\n\nEmail with a *text attachment*.\n\n{{body2}}\n\n--001a113c48b0b89d89052d3051d8\nContent-Type: text/html; charset=UTF-8\n\n<div dir=\"ltr\"><div>Email with a <i>text attachment</i>.</div>\n\n{{body1}}\n</div>\n\n--001a113c48b0b89d89052d3051d8--\n--001a113c48b0b89d92052d3051da\nContent-Type: text/plain; charset=US-ASCII; name=\"myfile.txt\"\nContent-Disposition: attachment; filename=\"myfile.txt\"\nContent-Transfer-Encoding: base64\nX-Attachment-Id: f_ild455ce0\n\nVGhpcyBpcyBteSBzaW1wbGUgdGV4dCBmaWxlLgo=\n--001a113c48b0b89d92052d3051da--"
  },
  "name": "_TMP_TEMPLATE_TEST"
}

请求完成后,SparkPost将返回您的新模板的唯一标识符。例如xxxxxxx

发送模板

好消息是创建 RFC 5322 内容是困难的部分。从现在开始,使用 SparkPost 发送该模板与发送任何其他模板完全相同。

以下是我们如何发送该模板并填充替换数据:

{
  "campaign_id": "MyCampaign",
  "return_path": "myReturnPath@yourdomain.com",
  "substitution_data": {
    "replyto": "myReplyToh@yourdomain.com",
    "from": "MyFrom@yourdomain.com",
    "subject": "my subject",
    "body1": "Extra content for the HTML part",
    "body2": "Extra content for the text part"
  },
  "recipients": [
    {
      "substitution_data": {},
      "address": {
        "email": "test1@domain.com",
        "name": "test1"
      }
    }
  ],
  "content": {
    "template_id": "xxxxxxx",
    "use_draft_template": true
  }
}

来自邮件客户端 API 的模板

如果您正在使用一种具有电子邮件编写库的编程语言,您可以使用它来以编程方式创建模板,甚至内联发送消息。 以下是使用JavaMail通过SparkPost的传输端点的示例。该方法应该可以轻松转换为PHP或您选择的语言。

/**
 * Demonstration of using JavaMail MIME message with the SparkPost RESTful interface
 */
public class App extends SparkPostBaseApp {
    public static void main(String[] args) throws Exception {
        Logger.getRootLogger().setLevel(Level.DEBUG);
        App app = new App();
        app.runApp();
    }
    private void runApp() throws Exception {
        Message message = createMultipartMessage();
        // Convert JavaMail message into a string for transmission
        String rfc822Content = getMessageAsString(message);
        // Add dynamic To and From using SparkPost substitution syntax
        rfc822Content = "To: {{address.email}}\r\nFrom: {{from}}\r\n" + rfc822Content;
        String fromAddress = getFromAddress();
        String[] recipients = getTestRecipients();
        sendEmail(fromAddress, recipients, rfc822Content);
    }
    private void sendEmail(String from, String[] recipients, String email)
            throws SparkPostException, IOException {
        Client sparkpostClient = newConfiguredClient();
        TransmissionWithRecipientArray transmission = new TransmissionWithRecipientArray();
        // Populate Recipients
        List<RecipientAttributes> recipientArray = new ArrayList<>();
        for (String recipient : recipients) {
            RecipientAttributes recipientAttribs = new RecipientAttributes();
            recipientAttribs.setAddress(new AddressAttributes(recipient));
            recipientArray.add(recipientAttribs);
        }
        transmission.setRecipientArray(recipientArray);
        transmission.setReturnPath(from);
        // Populate Substitution Data
        Map<String, String> substitutionData = new HashMap<>();
        substitutionData.put("from", from);
        substitutionData.put("name", "Your Name Here");
        transmission.setSubstitutionData(substitutionData);
        // Populate Email Body with RFC822 MIME
        TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
        contentAttributes.setEmailRFC822(email);
        transmission.setContentAttributes(contentAttributes);
        // Send Email
        RestConnection connection = new RestConnection(sparkpostClient, getEndPoint());
        Response response = ResourceTransmissions.create(connection, 0, transmission);
        if (response.getResponseCode() == 200) {
            System.out.println("✅ Transmission Response: " + response);
        } else {
            System.err.println("❌ TRANSMISSION ERROR: " + response);
        }
    }
    /**
     * Builds an email with text, HTML, and attachment parts
     */
    private Message createMultipartMessage() throws MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.host", "none"); // Required for JavaMail to work
        Session session = Session.getDefaultInstance(props, null);
        Message message = new MimeMessage(session);
        message.setSubject("A multipart MIME message demo");
        // Main multipart container
        Multipart multiPart = new MimeMultipart("mixed");
        // Sub multipart for text + HTML
        MimeMultipart altPart = new MimeMultipart("alternative");
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText("{{name}},\r\nplain text content", "utf-8");
        // HTML part
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent("<b>{{name}},<br><br>Our HTML content</b>", "text/html; charset=utf-8");
        // Add text and HTML to the alternative container
        altPart.addBodyPart(textPart);
        altPart.addBodyPart(htmlPart);
        // Wrap alternative part in a MimeBodyPart so it can be added to mixed container
        MimeBodyPart altBodyPart = new MimeBodyPart();
        altBodyPart.setContent(altPart);
        // Add alternative section to mixed container
        multiPart.addBodyPart(altBodyPart);
        // Add attachment
        MimeBodyPart attachmentPart = new MimeBodyPart();
        String filename = "java_SparkPost_background.pdf";
        DataSource source = new FileDataSource(filename);
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setFileName(filename);
        multiPart.addBodyPart(attachmentPart);
        // Set full content
        message.setContent(multiPart);
        return message;
    }
    /**
     * Converts a JavaMail message into an RFC822 string
     */
    private String getMessageAsString(Message msg) throws IOException, MessagingException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            msg.writeTo(out);
            return out.toString("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 not found! " + e.getMessage());
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

结论

现在您已经了解SparkPost如何用于发送几乎任何复杂性的电子邮件,您可能会想看看“SparkPost Supports Sending Email on Apple Watch”或查看替换语法,以了解如何在您的模板或传输内容中使用“if then else”、“条件表达式”或“数组迭代”。

其他新闻

阅读更多来自此类别的内容

A person is standing at a desk while typing on a laptop.

完整的AI原生平台,可与您的业务一起扩展。

© 2025 Bird

A person is standing at a desk while typing on a laptop.

完整的AI原生平台,可与您的业务一起扩展。

© 2025 Bird