Search code examples
c#brevo

Unable to pass the custom attribute to brevo template using c#


I am trying to send an email using Brevo by having the existing template able to send the email but not able to see the updated property in the email. Here is my code

static void Main(string[] args)
{
    string apiKey = "";

    // API endpoint for sending SMTP emails
    string apiUrl = "https://api.sendinblue.com/v3/smtp/email";

    // Example email data with template
    var emailData = new
    {
        sender = new { email = "[email protected]", name = "A" },
        to = new List<object> { new { email = "[email protected]" } },
        templateId = 1, // Template ID from Brevo
        **value = new Dictionary<string, object>
        {
            { "EMPLOYEENAME", "MYNAME" },
        }**
    };

    // Serialize email data to JSON
    string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(emailData);

    // Create HTTP client instance
    using (var client = new HttpClient())
    {
        // Add API key to request headers
        client.DefaultRequestHeaders.Add("api-key", apiKey);

        try
        {
            // Create HTTP POST request
            var response = client.PostAsync(apiUrl, new StringContent(jsonData, Encoding.UTF8, "application/json")).Result;

            // Check if request was successful
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Email sent successfully.");
            }
            else
            {
                string errorMessage = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine($"Failed to send email. Error: {errorMessage}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error sending email: {ex.Message}");
        }
    }
}

I am trying to replace this but somehow it is not working

**value = new Dictionary<string, object>
            {
                { "EMPLOYEENAME", "MYNAME" },
            }**

This is my template builder enter image description here

This is what I added in my contact attributes

enter image description here

Adding the template design

enter image description here


Solution

  • I guess the reason of it is that you pass arguments into a template using value. You should pass them using params, atleast that is what documentations says. So try something like it:

    var emailData = new
        {
            sender = new { email = "[email protected]", name = "A" },
            to = new List<object> { new { email = "[email protected]" } },
            templateId = 1, // Template ID from Brevo
            @params= new Dictionary<string, object>
            {
                { "EMPLOYEENAME", "MYNAME" },
            }
        };