Setting email headers through Mailgun API not working

I’m working with Mailgun API on my Node.js application and running into issues with email headers. No matter what I try, the custom headers I’m setting just don’t show up in the sent emails.

I need to add List-Unsubscribe and List-Unsubscribe-Post headers but even basic test headers aren’t working. When I check the Mailgun delivery logs, none of my custom headers appear.

Here’s my current setup:

const emailData = {
  recipient: userEmail,
  sender: config.fromAddress,
  emailSubject: messageSubject,
  templateName: NotificationTemplate.Reminders,
  "v:dashboardUrl": `${getDomainUrl()}/dashboard`,
  "v:settingsUrl": `${getDomainUrl()}/settings`,
  "v:supportUrl": `${getDomainUrl()}/help`,
  "v:userName": userData.name,
  "h:List-Unsubscribe": "<https://example.com/unsubscribe>, <mailto:[email protected]>",
  "h:List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
  "h:X-Priority": "3",
  "h:X-Mailer": "MyApp",
  "h:Return-Path": "[email protected]",
  "h:test-header": "test-value"
};

await mailgunClient.messages().send(emailData);

Only the basic fields like recipient, sender, subject work along with the template variables starting with v:. All the h: prefixed headers get ignored completely. Has anyone faced this before?

This might be a payload structure issue. I ran into the same thing last year - Mailgun’s Node.js client wants headers as a separate parameter, not mixed in with your other email data. Try this:

const headers = {
  "List-Unsubscribe": "<https://example.com/unsubscribe>, <mailto:[email protected]>",
  "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
  "X-Priority": "3"
};

const messageData = {
  from: config.fromAddress,
  to: userEmail,
  subject: messageSubject,
  template: NotificationTemplate.Reminders,
  'h:': headers
};

Also, some client versions need you to flatten the headers object completely. Check your mailgun-js package version - the API changed a lot between releases.

I encountered a similar issue when implementing email headers with Mailgun. It appears that you’re not separating the headers correctly. Mailgun typically requires you to define the headers in a specific way when using their API. Try creating a separate headers object and include it in your API call. Additionally, verify that your Mailgun domain is configured correctly. I spent considerable time troubleshooting only to discover that my domain needed verification for custom headers to work. Also keep in mind that some email clients may strip certain headers, so it might be worth testing with a raw viewer.

check your mailgun endpoint first - I had this same issue and was hitting the wrong api url. also verify your api key has permissions for custom headers. some restricted keys block this feature.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.