0
votes

I am unable to get word substitution to work consistently with sendgrid v3 api in c#. Sometimes the tags will be substituted, other times they will not. I am at a loss as to what causes this. Can anyone see any obvious errors in my code?

            String apiKey = "KEY";
            dynamic sg = new SendGridAPIClient(apiKey);

            Email from = new Email("[email protected]");
            String subject = "Hello World from the SendGrid CSharp Library";
            Email to = new Email("[email protected]");
            Content content = new Content("text/html", " ");
            to.Name = "Joe";

            Mail mail = new Mail(from, subject, to, content);
            mail.TemplateId = "dfea45f3-d608-4860-9f38-c7d444qwrqwc1f";

            Personalization subs = new Personalization();
            subs.AddTo(to);
            subs.AddSubstitution("*|url|*", "http://asdasdasd.com");
            subs.AddSubstitution("*|username|*", "MrUsername");

            mail.AddPersonalization(subs);

            dynamic response = sg.client.mail.send.post(requestBody: mail.Get());
2
Hi, have you able to solve the problem? Thanks for your response! Got the same issue - Lyubomir Velchev
No, i emailed sendgrid but go no response yet. - loveforfire33

2 Answers

1
votes

Remove the Personalization and add the following

mail.Personalization[0].AddSubstitution("*|url|*", "http://asdasdasd.com");
mail.Personalization[0].AddSubstitution("*|username|*", "MrUsername");

or see code samples here

0
votes

I have found the issue my side. I think yours is the same. When you look at mail object before sending you will find there are 2 personification items in the array. You do this subs.AddTo(to); then later on mail.AddPersonalization(subs); This creates 2 email to in the personalization array - my example of the wrong payload was:

{
    "from": {
        "email": "[email protected]"
    },
    "subject": "",
    "personalizations": 
    [
        {
        "to": [{
            "email": "[email protected]"
        }]
        },
        {
        "to": [{
            "email": "[email protected]"
        }],
        "substitutions": {
            ":token": "http://alabala.com/auth/reset-password#token=or514rqHTeLjtjlN6WRppOu53yJJ64nSzcK86GF6Ite2BaZRa58YPMfTmM0wzQs4tMLbHy8YlpieDVBae1aD99TKnMh7wYNOE2nmu8gWePQoZiWhbFLomVBvApHA1fuxIxQ1elui2QXAmGPtwDdvVOgvAiSF3HQteuvFwP5kXUnXXEeddYLIUHqJCDrATiOsSgxvcpKmhXhrhx78ns49f4hakGlLMncNgBuMGmL3wCduY9f22hjCs9tbIPq5h5V"
        }
        }
    ],
    "content": [{
        "type": "text/html",
        "value": "\u003chtml\u003e\u003cbody\u003eHTML content\u003c/body\u003e\u003c/html\u003e"
    }],
    "template_id": "unique id"
}

' Check your payload and to fix it try mail.AddPersonalization[0] = subs; Hope this solves your issue