Skip to content

Custum variables not parsed #142

@laslingerland

Description

@laslingerland

I have created a template (6675577) in Mailjet and I use it to send transactional emails from my web application. Now the template is used, but the variables that I send to it, aren't parsed. The received email does show the unsubscribe message with parsed variables, but the First Name, Password and LoginUrl aren't parsed at all. I have tried the {{var:}} syntax, but it breaks the template and emails using it are blocked. The Nuget packages is strongly typed here, so I must use Dictionary<string, object>.

This message seems to be a duplicate of #78, but there it was closed because of inactivity and I simply can't get it to work. Not with Google, not with Copilot, simply not.

public class MailjetEmailService(ISecretProvider secretProvider, IConfiguration configuration) : IEmailService
{
    public async Task SendWelcomeEmailAsync(User user, string password)
    {
        const string subject = "Welcome";
        
        if (!long.TryParse(configuration["Mailjet:Templates:Welcome"], out var templateId))
        {
            throw new InvalidCastException("Invalid Mailjet TemplateID");
        }

        var frontendUrl = configuration["Frontend:Url"];
        if (frontendUrl == null)
        {
            throw new MissingAppSettingException("Frontend:Url");
        }
        
        var variables = new Dictionary<string, object>
        {
            {"FIRSTNAME", user.FirstName},
            {"PASSWORD", password},
            {"LOGINURL", frontendUrl}
        };

        await SendEmailAsync(user.Email, user.FullName, subject, templateId, variables);
    }
    
    private async Task SendEmailAsync(string to, string toName, string subject, long templateId, IDictionary<string, object> variables)
    {
        var apiKey = secretProvider.GetSecret("MailjetApiKey");
        var secretKey = secretProvider.GetSecret("MailjetSecretKey");
        
        var client = new MailjetClient(apiKey, secretKey);

        var email = new TransactionalEmailBuilder()
            .WithFrom(new SendContact("from@address.com", "FromName"))
            .WithSubject(subject)
            .WithTemplateId(templateId)
            .WithTemplateLanguage(true)
            .WithVariables(variables)
            .WithTo(new SendContact(to, toName))
            .Build();

        var response = await client.SendTransactionalEmailAsync(email);

        if (response.Messages.Length == 1)
        {
            Log.Information("Email sent with subject {Subject}", subject);
        }
        else
        {
            Log.Warning("Failed to send email with subject {Subject}", subject);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions