3

I am trying to send an email with a specific dynamic template and data. Email is successfully sent but contains empty data. The handle method is part of Azure Function. Recently I've changed Newtonsoft JSON to System.Text.Json and maybe this causes some problems.

Email: enter image description here

SendGrid dynamic template configuration: enter image description here

C# Code:

        public async Task Handle(SendEmailCommand command)
        {
            var client = new SendGridClient(emailConfig.SendGridApiKey);
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(emailConfig.Sender));
            msg.AddTo(new EmailAddress(command.To));
            msg.SetTemplateId(command.SendGridTemplateId);

            if (command.SendGridDynamicTemplateData != null)
            {
                var templateData = new TemplateData();

                command.SendGridDynamicTemplateData.TryGetValue("topic", out var topic);
                command.SendGridDynamicTemplateData.TryGetValue("email", out var email);
                command.SendGridDynamicTemplateData.TryGetValue("name", out var name);
                command.SendGridDynamicTemplateData.TryGetValue("message", out var message);

                templateData.Topic = topic.ToString();
                templateData.Email = email.ToString();
                templateData.Name = name.ToString();
                templateData.Message = message.ToString();

                msg.SetTemplateData(templateData);
            }

            await client.SendEmailAsync(msg);
        }

        private class TemplateData
        {
            [JsonPropertyName("topic")]
            public string Topic { get; set; }

            [JsonPropertyName("email")]
            public string Email { get; set; }

            [JsonPropertyName("name")]
            public string Name { get; set; }

            [JsonPropertyName("message")]
            public string Message { get; set; }
        }

Am I doing something wrong?

tzm
  • 588
  • 1
  • 12
  • 27

1 Answers1

1

I noticed the same thing. The [JsonPropertyName] attribute from System.Text.Json doesn't seem to be recognized by the SendGrid API. I had to use the [JsonProperty] attribute from Newtonsoft.Json in order to get the parameters to appear on the email.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Toni
  • 11
  • 2
  • It looks like SendGrid API doesn't work properly with System.Text.Json which is a recommended serializer for .NET Core right now (faster than Newtonsoft.Json) – tzm Oct 17 '20 at 17:30
  • Even worse it appears api will not let you just give them the JSON directly – JMIII Aug 06 '21 at 17:03