# nodemailer, how to embed an image into an email

> Learn how to embed an image in a nodemailer email by reading it with fs.readFileSync, encoding it as a base64 data URI, and dropping it into the HTML body.

Author: Flavio Copes | Published: 2023-05-11 | Canonical: https://flaviocopes.com/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:

```javascript
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) ](https://flaviocopes.com/fix-dirname-not-defined-es-module-scope/)[`__dirname`](https://flaviocopes.com/fix-dirname-not-defined-es-module-scope/)[ is not available](https://flaviocopes.com/fix-dirname-not-defined-es-module-scope/) 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:

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

Transform that into a base64-encoded string:

```javascript
const src = `data:image/jpg;base64,${Buffer.from(
  imageData,
  'binary'
).toString('base64')}`
```

Finally you can add that to the email body:

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