Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic template data for multiple recipients #86

Open
JayCunha opened this issue Nov 10, 2020 · 4 comments
Open

Dynamic template data for multiple recipients #86

JayCunha opened this issue Nov 10, 2020 · 4 comments

Comments

@JayCunha
Copy link

Actual Behaviour

Right now, I can only send dynamic template data for one recipient at a time. Example of my code:

{
"personalizations": [
{
"to": [
{
"email": "[email protected]",
"name": "John Doe"
}
],
"dynamic_template_data": {
"firstName": "John",
"lastName": "Doe"
},
"subject": "Hello, World!"
}
],
"from": {
"email": "[email protected]",
"name": "John Doe"
},
"reply_to": {
"email": "[email protected]",
"name": "John Doe"
},
"template_id": "<<YOUR_TEMPLATE_ID>>"
}

Expected Behaviour

I want to send dynamic template data for each recipient, but I don't know how. The idea is to send personalized e-mails for multiple recipients one at a time, instead of sending emails one by one. I tried to search for an example but I couldn't find it. Do you have any?

@hmtanbir
Copy link

Yes, you can send one mail to multiple recipient. I have faced same problem but I have solved the issue. Just use separate personalizations.
Example Json:

{
  "personalizations": [
    {
      "to": [
        {
          "email": "[email protected]",
          "name": "John Doe"
        }
      ],
      "dynamic_template_data": {
        "firstName": "John",
        "lastName": "Doe"
      },
      "subject": "Hello, World!"
    },
    {
      "to": [
        {
          "email": "[email protected]",
          "name": "John Doe"
        }
      ],
      "dynamic_template_data": {
        "firstName": "John",
        "lastName": "Doe"
      },
      "subject": "Hello, World!"
    }
  ],
  "from": {
    "email": "[email protected]",
    "name": "John Doe"
  },
  "reply_to": {
    "email": "[email protected]",
    "name": "John Doe"
  },
  "template_id": "<<YOUR_TEMPLATE_ID>>"
}

@logany-hi
Copy link

Since this issue hasn't been closed, how do I inject my dynamic template data into the model when using the SendGridMessage object in C#?

var mail = new SendGridMessage
{
    Attachments = new List<Attachment>(),
    From = new EmailAddress()
    {
        Email = emailConfig.FromAddress,
        Name = emailConfig.FromName
    },
    TemplateId = EmailConstants.ConfirmationEmailTemplateId,
    Subject = subject
};

mail.Personalizations = new List<Personalization>() {
    TemplateData = ???
};

@tofy
Copy link

tofy commented Jun 21, 2022

@logany-hi

For you reference:-

public virtual async Task<bool> SendEmailPersonalized<TValue>(Dictionary<string, string> to, string templateId, Dictionary<string, TValue> templateData, string? fromName = null, string? fromEmail = null)
    {
        var msg = new SendGridMessage();
        msg.SetFrom(new EmailAddress(fromEmail ?? sendGridOptions.FromEmail, fromName ?? sendGridOptions.FromName));
        msg.SetTemplateId(templateId);

        msg.Personalizations = new List<Personalization>();

        foreach (var r in to)
        {
            msg.Personalizations.Add(new Personalization()
            {
                Tos = new List<EmailAddress>() { new EmailAddress(r.Key, r.Value) },
                TemplateData = templateData[r.Key]
            }); 
        }

        var response = await sendGridClient.SendEmailAsync(msg);
        if (response.StatusCode >= System.Net.HttpStatusCode.OK && response.StatusCode <= System.Net.HttpStatusCode.IMUsed)
        {
            return true;
        }

        logger.LogWarning("SendEmail returned a negative status. Response: {@response} for {@to} address. TemplateId: {@templateId}", response, to, templateId);
        return false;
    }


//-------------------------------
//Caller of above function
//-------------------------------
foreach (var t in alertsList)
        {
            await _emailService.SendEmailPersonalized(
                t.AlertRecipient.ToDictionary(a => a.Email??Notifications.CommonData.Empty_UserEmail_Replacement, a => a.Name??Notifications.CommonData.Empty_UserName_Replacement)
                ,alertType.TemplateId!
                ,t.AlertRecipient.ToDictionary(a => a.Email?? Notifications.CommonData.Empty_UserEmail_Replacement, a => new CampaignGoalAchieved
                {
                    DonorName = a.Name??Notifications.CommonData.Empty_UserName_Replacement,
                    CampaignName = "Test Campaign Name",
                    CampaignLink = "http://sample.com",
                    GoalAchieved = "25"
                })
                , alertType.Sender
                , alertType.SenderEmail
            );

            t.Status = Notifications.AlertStatus.Processed;
            await UpdateAlertAsync(_Mapper.Map<Alert, AlertDto>(t));
        }

@RazGvili
Copy link

RazGvili commented Mar 5, 2023

I also had issues with it.
The docs are pretty disappointing :(

What worked for me -
create a separate object for each email. Not using the personalization key.

example:

const yourArrayOfEmails = [{someData: 1, email: '[email protected]'}, {someData: 2, email: '[email protected]'}]

yourArrayOfEmails.map(emailDetails => {
  return {
    from: {
        email: EMAIL_FROM,
        name: EMAIL_NAME,
    },
    templateId: EMAIL_TEMPLATE_ID,
  
    // dynamic
    to: emailDetails.email,
    dynamicTemplateData: {
        someData: emailDetails.someData,
    },
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants