I’m trying to figure out how to include inline images in my emails when using Mailgun with Node.js. The official docs show this example but it’s only for curl commands:
-F inline=@assets/myimage.jpg
I’ve been working on my own implementation but the images aren’t showing up in the emails. Here’s my current code:
Mailgun.sendHtmlEmail({
apiKey: 'my-api-key',
domain: 'my-domain.com',
toEmail: user.email,
toName: user.name,
subject: 'Welcome Email',
htmlMessage: '<html><img style="display:block;" src="cid:welcome.png" width="500" height="100" /></html>',
inline: 'images/welcome.png',
fromEmail: '[email protected]',
fromName: 'MyApp Team'
}).exec({
error: function (error){
console.log('Email failed:', error);
},
success: function (){
console.log('Email sent successfully');
}
});
The email sends fine but no image appears. I think the issue is with how I’m referencing the inline file path. Does Node.js need a specific way to access these files? What’s the correct approach for handling inline images with Mailgun in a Node.js environment?
you gotta use fs.createReadStream() to read the file right. try using inline: fs.createReadStream('./images/welcome.png') instead of just a path string. mailgun needs that file stream, not just a reference.
Been dealing with this exact issue recently and found that most Mailgun wrapper libraries handle inline attachments differently than the raw API. The key thing missing from your code is that you need to pass the inline parameter as an array, even for single images. Here’s what worked for me:
const fs = require('fs');
Mailgun.sendHtmlEmail({
// your existing config
inline: [{
filename: 'welcome.png',
data: fs.createReadStream('./images/welcome.png'),
cid: 'welcome.png'
}],
// rest of parameters
});
The crucial part is explicitly setting the cid property to match what you reference in your HTML. Without that explicit mapping, Mailgun can’t properly link the inline attachment to your HTML content. Also double-check that your file path is correct relative to where your Node.js script is running from.
The problem is that you’re mixing up the attachment format with the inline format. When using the Mailgun Node.js SDK, inline images need to be handled as file objects with specific properties. Your inline parameter should be structured as an object with the filename and data stream. Try modifying your code like this:
const fs = require('fs');
Mailgun.sendHtmlEmail({
// your other parameters
inline: {
filename: 'welcome.png',
data: fs.readFileSync('./images/welcome.png')
}
// rest of your config
});
Also make sure your HTML references match the filename exactly. The cid:welcome.png should correspond to the filename property. I had similar issues when I first started with Mailgun and this approach resolved the inline image rendering problems.