How to incorporate custom variables in Mailgun API HTML content?

I’m trying to send emails through Mailgun API with my own HTML content. I want to add custom variables to the email body but they’re not showing up. Here’s what I’ve done:

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': '<p>Hello {{user_name}}, welcome to our service!</p>',
        'subject': 'Welcome Email',
        'h:X-Mailgun-Variables': json.dumps({'user_name': 'John Doe'})
    }
)

The email sends fine, but the {{user_name}} doesn’t get replaced. Do I need to upload my HTML as a template first? Or is there another way to use custom variables with inline HTML? Any help would be great!

It seems you’re close, but there’s a small adjustment needed. When using inline HTML with custom variables, you should use the ‘v:’ prefix for your variables in the X-Mailgun-Variables header. Try modifying your code like this:

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': '<p>Hello %recipient.user_name%, welcome to our service!</p>',
        'subject': 'Welcome Email',
        'v:user_name': 'John Doe'
    }
)

This approach should work without needing to create a separate template. The %recipient.variable_name% syntax is used in the HTML for variable substitution. Make sure to use the ‘v:’ prefix when defining variables in your request data. This method allows for inline variable replacement without additional setup.

I’ve had success using Mailgun’s templating system for custom variables. In my experience, the key is to set up your template in the Mailgun dashboard with placeholders like {{user_name}} and then refer to that template when sending your message. Instead of using inline HTML, I switched to using the ‘template’ parameter and provided the custom variables via the ‘t:variables’ field. For example, I wrote my Python code like this:

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': 'your_template_name',
        'subject': 'Welcome Email',
        't:variables': json.dumps({'user_name': 'John Doe'})
    }
)

This approach not only simplifies managing dynamic content but also ensures that variable substitution works reliably.

hey man, have u tried using mailgun templates? they’re super easy to set up n use. just create a template with ur variables like {{user_name}} in the mailgun dashboard, then in ur code use the ‘template’ parameter instead of ‘html’. pass ur variables with ‘t:variables’. should work like a charm!