Skip to content

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}">`,
}

→ Get my Node.js Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about node: