Home > Enterprise >  Node JS reading local image file and use them in html files
Node JS reading local image file and use them in html files

Time:12-22

For nodemailer. Tried reading a local image (png) and attaching it to the custom HTML template (img tag). but the image is not getting displayed in the email. Either it is broken or displaying some random characters.

Tried using readSync, Buffer.from with formats utf-8, base64, base64url.

Folder structure & sample code

src
├── index.ts
├── _assets
│   ├── image.png

const imgData = fs.readFileSync('/path/to/file.png', {encoding: 'base64'});
const htmlTemplate = `
<html><body>
<img src=${img}/>
</body></html>`

await transporter.sendMail({
from: '',
to: '',
subject: '', 
text: '', 
html: imgData});

Can't use express static approach, because creating a node package.

CodePudding user response:

You need to provide a data url to image source.

const imgData = fs.readFileSync('fileee.png', {encoding: 'base64'});
const htmlTemplate = `
<html><body>
<img src="data:image/png;base64,${imgData}"/>
</body></html>`
  • Related