Injecting variables into HTML templates with Mailgun API

I’m trying to send emails using Mailgun’s API but I’m having trouble with variable injection. My HTML template is included directly in the API request rather than being pre-uploaded to Mailgun.

The template looks like this:

<html>THIS IS THE TEMPLATE {{my_var}}</html>

And here’s my Python code:

response = requests.post(
    'https://api.mailgun.net/v3/mydomain.com/messages',
    auth=('api', 'my-api-key'),
    data={
        'from': 'Sender <[email protected]>',
        'to': ['[email protected]'],
        'html': '<html>THIS IS THE TEMPLATE {{my_var}}</html>',
        'subject': 'Test Email',
        'text': 'Plain text version',
        'h:X-Mailgun-Variables': json.dumps({'my_var': 'Test Value'})
    }
)

The variable isn’t being replaced in the email. Do I need to upload my template to Mailgun first? The docs only show examples using the ‘template’ parameter, not ‘html’. Any help would be great!

I’ve actually tackled this issue before in a project. The key is to use Mailgun’s template engine properly. Instead of putting the HTML directly in the ‘html’ field, you should use the ‘template’ parameter and then provide your variables separately.

Here’s what worked for me:

response = requests.post(
    'https://api.mailgun.net/v3/mydomain.com/messages',
    auth=('api', 'my-api-key'),
    data={
        'from': 'Sender <[email protected]>',
        'to': ['[email protected]'],
        'template': '<html>THIS IS THE TEMPLATE %recipient.my_var%</html>',
        'subject': 'Test Email',
        'text': 'Plain text version',
        'recipient-variables': json.dumps({'[email protected]': {'my_var': 'Test Value'}})
    }
)

Notice the use of %recipient.my_var% instead of {{my_var}}. This syntax is specific to Mailgun’s template engine. Also, the variables are passed using ‘recipient-variables’ instead of ‘h:X-Mailgun-Variables’.

This approach should work without needing to pre-upload your template. Give it a try and let me know if you run into any issues!

hey emma, i had the same issue. try using the ‘template’ parameter instead of ‘html’ in ur data dict. like this:

data = {

‘template’: ‘THIS IS THE TEMPLATE {{my_var}}’,

}

that shud work for inlining templates w/ variables. hope it helps!