nodemailer, how to embed an image into an email

🆕 🔜 Check this out if you dream of running a solo Internet business 🏖️

I had the need to send an image to an email I was sending with nodemailer.

I tried using an attachment but.. the image was added as attachment.

So I embedded the image as base64 into the email body.

First I added some 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)

We need to do that __filename and __dirname stuff because with ES modules (import syntax) __dirname is not available and we have to reference a file with fs.readFileSync() but that wants absolute paths, not relative ones.

Long story short, do that.

Now read the image:

const imageData = fs.readFileSync(__dirname + '/image.jpg', 'binary')

Transform that into a base64-encoded string:

const src = `data:image/jpg;base64,${Buffer.from(

Finally you can add that to the email body:

const mailOptions = {
  html: `<img style="width:800px;" src="${src}">`,