Skip to content

Commit

Permalink
Add Dynamic Template Support
Browse files Browse the repository at this point in the history
  • Loading branch information
carl-underwood committed Aug 16, 2018
1 parent f39a5c7 commit 75de374
Show file tree
Hide file tree
Showing 7 changed files with 696 additions and 48 deletions.
139 changes: 137 additions & 2 deletions USE_CASES.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ This documentation provides examples for specific use cases. Please [open an iss
* [Email - Send a Single Email to Multiple Recipients](#singleemailmultiplerecipients)
* [Email - Send a Single Email to a Single Recipient](#singleemailsinglerecipient)
* [Email - Send Multiple Emails to Multiple Recipients](#multipleemailsmultiplerecipients)
* [Email - Transactional Templates](#transactional-templates)
* [Email - Dynamic Transactional Templates](#dynamic-transactional-templates)
* [Email - _Legacy_ Transactional Templates](#transactional-templates)
* [Transient Fault Handling](#transient-faults)
* [How to Setup a Domain Whitelabel](#domain-whitelabel)
* [How to View Email Statistics](#email-stats)
Expand Down Expand Up @@ -467,8 +468,142 @@ namespace Example
}
```

<a name="dynamic-transactional-templates"></a>
# Dynamic Transactional Templates

For this example, we assume you have created a [dynamic transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/Create_and_edit_dynamic_transactional_templates.html).
Following is the template content we used for testing.

Template ID (replace with your own):

```text
d-d42b0eea09964d1ab957c18986c01828
```

Email Subject:

```text
Dynamic Subject: {{subject}}
```

Template Body:

```html
<html>
<head>
<title></title>
</head>
<body>
Hello {{name}},
<br /><br/>
I'm glad you are trying out the dynamic template feature!
<br /><br/>
I hope you are having a great day in {{city}} :)
<br /><br/>
</body>
</html>
```

## With Mail Helper Class

```csharp
using SendGrid;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;
using System;

namespace Example
{
internal class Example
{
private static void Main()
{
Execute().Wait();
}

static async Task Execute()
{
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage();
msg.SetFrom(new EmailAddress("[email protected]", "Example User"));
msg.AddTo(new EmailAddress("[email protected]", "Example User"));
msg.SetTemplateId("d-d42b0eea09964d1ab957c18986c01828");
msg.AddDynamicTemplateDataValue("subject", "Hi!");
msg.AddDynamicTemplateDataValue("name", "Example User");
msg.AddDynamicTemplateDataValue("city", "Birmingham");
var response = await client.SendEmailAsync(msg);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Headers.ToString());
Console.WriteLine("\n\nPress any key to exit.");
Console.ReadLine();
}
}
}
```

Methods also exist on `MailHelper` to create dynamic template emails:
* `CreateSingleDynamicTemplateEmail`
* `CreateSingleDynamicTemplateEmailToMultipleRecipients`
* `CreateMultipleDynamicTemplateEmailsToMultipleRecipients`

## Without Mail Helper Class

```csharp
using Newtonsoft.Json;
using System.Threading.Tasks;
using System;
using SendGrid;

namespace Example
{
internal class Example
{
private static void Main()
{
Execute().Wait();
}

static async Task Execute()
{
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);

string data = @"{
'personalizations': [
{
'to': [
{
'email': '[email protected]'
}
],
'dynamic_template_data': {
'subject': 'Hi!',
'name': 'Example User',
'city': 'Birmingham'
}
}
],
'from': {
'email': '[email protected]'
},
'template_id': 'd-d42b0eea09964d1ab957c18986c01828'
}";
var json = JsonConvert.DeserializeObject<Object>(data);
var response = await client.RequestAsync(method: SendGridClient.Method.POST,
requestBody: json.ToString(),
urlPath: "mail/send");
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Headers.ToString());
Console.WriteLine("\n\nPress any key to exit.");
Console.ReadLine();
}
}
}
```

<a name="transactional-templates"></a>
# Transactional Templates
# _Legacy_ Transactional Templates

For this example, we assume you have created a [transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). Following is the template content we used for testing.

Expand Down
111 changes: 110 additions & 1 deletion src/SendGrid/Helpers/Mail/MailHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
// </copyright>

namespace SendGrid.Helpers.Mail
{
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

Expand Down Expand Up @@ -52,6 +53,38 @@ public static SendGridMessage CreateSingleEmail(
return msg;
}

/// <summary>
/// Send a single dynamic template email
/// </summary>
/// <param name="from">An email object that may contain the recipient’s name, but must always contain the sender’s email.</param>
/// <param name="to">An email object that may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="templateId">The ID of the template.</param>
/// <param name="dynamicTemplateData">The data with which to populate the dynamic template.</param>
/// <returns>A SendGridMessage object.</returns>
public static SendGridMessage CreateSingleDynamicTemplateEmail(
EmailAddress from,
EmailAddress to,
string templateId,
Dictionary<string, string> dynamicTemplateData)
{
if (string.IsNullOrWhiteSpace(templateId))
{
throw new ArgumentException($"{nameof(templateId)} is required when creating a dynamic template email.", nameof(templateId));
}

var msg = new SendGridMessage();
msg.SetFrom(from);
msg.AddTo(to);
msg.TemplateId = templateId;

if (dynamicTemplateData != null)
{
msg.AddDynamicTemplateDataValues(dynamicTemplateData);
}

return msg;
}

/// <summary>
/// Send a single simple email to multiple recipients
/// </summary>
Expand Down Expand Up @@ -89,6 +122,44 @@ public static SendGridMessage CreateSingleEmailToMultipleRecipients(
return msg;
}

/// <summary>
/// Send a single simple email to multiple recipients
/// </summary>
/// <param name="from">An email object that may contain the recipient’s name, but must always contain the sender’s email.</param>
/// <param name="tos">A list of email objects that may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="templateId">The ID of the template.</param>
/// <param name="dynamicTemplateData">The data with which to populate the dynamic template.</param>
/// <returns>A SendGridMessage object.</returns>
public static SendGridMessage CreateSingleDynamicTemplateEmailToMultipleRecipients(
EmailAddress from,
List<EmailAddress> tos,
string templateId,
Dictionary<string, string> dynamicTemplateData)
{
if (string.IsNullOrWhiteSpace(templateId))
{
throw new ArgumentException($"{nameof(templateId)} is required when creating a dynamic template email.", nameof(templateId));
}

var msg = new SendGridMessage();
msg.SetFrom(from);
msg.TemplateId = templateId;

var setDynamicTemplateDataValues = dynamicTemplateData != null;

for (var i = 0; i < tos.Count; i++)
{
msg.AddTo(tos[i], i);

if (setDynamicTemplateDataValues)
{
msg.AddDynamicTemplateDataValues(dynamicTemplateData, i);
}
}

return msg;
}

/// <summary>
/// Send multiple emails to multiple recipients.
/// </summary>
Expand Down Expand Up @@ -129,6 +200,44 @@ public static SendGridMessage CreateMultipleEmailsToMultipleRecipients(
return msg;
}

/// <summary>
/// Send multiple emails to multiple recipients.
/// </summary>
/// <param name="from">An email object that may contain the recipient’s name, but must always contain the sender’s email.</param>
/// <param name="tos">A list of email objects that may contain the recipient’s name, but must always contain the recipient’s email.</param>
/// <param name="templateId">The ID of the template.</param>
/// <param name="dynamicTemplateData">The data with which to populate the dynamic template.</param>
/// <returns>A SendGridMessage object.</returns>
public static SendGridMessage CreateMultipleDynamicTemplateEmailsToMultipleRecipients(
EmailAddress from,
List<EmailAddress> tos,
string templateId,
List<Dictionary<string, string>> dynamicTemplateData)
{
if (string.IsNullOrWhiteSpace(templateId))
{
throw new ArgumentException($"{nameof(templateId)} is required when creating a dynamic template email.", nameof(templateId));
}

var msg = new SendGridMessage();
msg.SetFrom(from);
msg.TemplateId = templateId;

var setDynamicTemplateDataValues = dynamicTemplateData != null;

for (var i = 0; i < tos.Count; i++)
{
msg.AddTo(tos[i], i);

if (setDynamicTemplateDataValues)
{
msg.AddDynamicTemplateDataValues(dynamicTemplateData[i], i);
}
}

return msg;
}

/// <summary>
/// Uncomplex conversion of a <![CDATA["Name <[email protected]>"]]> to EmailAddress
/// </summary>
Expand Down
6 changes: 6 additions & 0 deletions src/SendGrid/Helpers/Mail/Model/Personalization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,11 @@ public class Personalization
/// </summary>
[JsonProperty(PropertyName = "send_at")]
public long? SendAt { get; set; }

/// <summary>
/// Gets or sets the dynamic template data object following the pattern "dynamic template data key":"dynamic template data value". All are assumed to be strings. These key value pairs will apply to the content of your dynamic template email, in addition to the subject and reply-to parameters.
/// </summary>
[JsonProperty(PropertyName = "dynamic_template_data", IsReference = false)]
public Dictionary<string, string> DynamicTemplateData { get; set; }
}
}
Loading

0 comments on commit 75de374

Please sign in to comment.