Are you looking for a way to send an image in an email using Nodemailer? Look no further! In this guide, we’ll walk you through the steps to embed an image directly into the email body instead of attaching it separately. Let’s get started!
First, let’s set up our environment by adding the necessary imports:
import fs from 'node:fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Please note that with ES modules (import syntax), __dirname
is not available by default. Therefore, we need to use the above method to work around this limitation. This will allow us to reference files using fs.readFileSync()
, which requires absolute paths.
Now, let’s read the image file:
const imageData = fs.readFileSync(path.join(__dirname, 'image.jpg'), 'binary');
Next, we’ll transform the image data into a base64-encoded string:
const src = `data:image/jpg;base64,${Buffer.from(imageData, 'binary').toString('base64')}`;
Finally, we can add the image to the email body using the html
option in the mailOptions
object:
const mailOptions = {
// ...
html: `<img style="width:800px;" src="${src}">`,
};
With these steps, you can now successfully embed an image into an email using Nodemailer.
Tags: nodemailer, email, image embedding