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}">`,
}
→ Download my free Node.js Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about node: