tekun
tekun

Reputation: 71

How to embed image to html mail in Node.js with SendGrid

I want to send HTML mail with some images.
I am using the library called 'sendgrid-nodejs'.
However, I can not do that and find any documentation related to it.

My Code.

const fs = require('fs');

function base64_encode(file) {
  var bitmap = fs.readFileSync(file);
  return new Buffer(bitmap).toString('base64');
};


const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'to address',
  from: 'from address',
  subject: 'subject',
  html: '<strong>Some Text</strong><img src="cid:12345" alt="test image" />',
  files: [
    {
      filename: 'test image',
      contentType: 'image/jpeg',
      cid: '12345',
      content: base64_encode('test.jpg')
    }
  ]
};

try {
  sgMail.send(msg)
} catch(err) {
  console.log(err)
}

If you need more information to solve this problem. Please tell me. Thank you.

Upvotes: 1

Views: 2171

Answers (1)

toonvanstrijp
toonvanstrijp

Reputation: 417

You need to add disposition: inline to your attachment.

const msg = {
  to: 'to address',
  from: 'from address',
  subject: 'subject',
  html: '<strong>Some Text</strong><img src="cid:12345" alt="test image" />',
  files: [
    {
      filename: 'test image',
      contentType: 'image/jpeg',
      cid: '12345',
      content: base64_encode('test.jpg'),
      disposition: 'inline'
    }
  ]
};

Upvotes: 3

Related Questions