'How to use Mailgun variable in email template?
I am using Mailgun API with nodejs+express to send emails. I want to transition into using templates instead of writing the whole email as the HTML tag in nodejs.
The Mailgun documentation shows how to send variables to the template but not how to use them inside the template.
This is how I'm sending the Mailgun request
const data = {
from: "Shared Video <[email protected]>",
to: shareTo,
subject: subject,
template: "share_video",
v: (subject = subject),
v: (shareToName = shareToName),
v: (userName = userName),
v: (videoTitle = videoTitle),
v: (videoID = videoID),
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
req.flash("success", "Video Shared");
res.redirect("/");
});
So how can I use those variables in the email template?
Solution 1:[1]
According to Mailgun Template Documentation you can pass template data using any of the 2 options provided below,
Option 1
const data = {
from: "Shared Video <[email protected]>",
to: shareTo,
subject: subject,
template: "share_video",
'h:X-Mailgun-Variables': JSON.stringify({
subject: subject,
shareToName: shareToName,
userName: userName,
videoTitle: videoTitle,
videoID: videoID
})
};
Option 2
const data = {
from: "Shared Video <[email protected]>",
to: shareTo,
subject: subject,
template: "share_video",
'v:subject': subject,
'v:shareToName': shareToName,
'v:userName': userName,
'v:videoTitle': videoTitle,
'v:videoID': videoID,
};
Finally, according to their documentation
The second way (Option 2 in our case) is not recomended as it’s limited to simple key value data. If you have arrays, dictionaries in values or complex json data you have to supply variables via
X-Mailgun-Variables
header.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kuttumiah |