nodemailer, how to embed an image into an email
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(
imageData,
'binary'
).toString('base64')}`
Finally you can add that to the email body:
const mailOptions = {
//...
html: `<img style="width:800px;" src="${src}">`,
}
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025