Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sendgrid multipart/alternative image from base64

I can't get Sendgrid (using node.js) to send an email with a embedded base64 image in the html. I think I'm quite close...

var base64img='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQgAAAFXCAYAAABeLtDdAAAgAElEQVR4Xu19CXhURdb2ISsJgSQ';//shortened version

sendgrid.send({
    to      : '[email protected]',
    from    : '[email protected]',
    subject : 'email with image from base64 data',
    headers:{
      'Content-Type':
      'multipart/alternative; boundary="imagebase64"'+
      '--imagebase64'+
      'Content-Type: image/png; name="base64.png"'+
      'Content-Disposition: inline; filename="base64.png"'+
      'Content-Transfer-Encoding: base64'+
      'Content-ID: <0123456789>'+
      'Content-Location: base64.png'+
      base64img+
      '--imagebase64'
      },
    html    : '<img src="cid:0123456789"/>'
    });

Can someone help, as I'm failing to find an example close on sendgrid docs or google

like image 372
Ben Muircroft Avatar asked Feb 16 '23 20:02

Ben Muircroft


1 Answers

FIXED!

  var base64img='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQgAAAFXCAYAAABeLtDdAAAgAElEQVR4Xu19CXhURdb2ISsJgSQ';//shortened version
  var data=base64img.replace(/^data:image\/\w+;base64,/,"");
  var buffer=new Buffer(data,'base64');
  fs.writeFile('/home/engine/public_html/img/base64img.png',buffer,function(err){
    fs.readFile('public_html/img/base64img.png',function(err,data){


    sendgrid.send({
      to      : '[email protected]',
      from    : '[email protected]',
      subject : 'email with image from base64 data',
      files   : [{filename:'base64.png',content:data,cid:'1234567890'}],
      html    : '<img src="cid:1234567890"/>'
      },
    function(success,message){
      if(!success){console.log(message);}
      else{
        console.log('sent');
        fs.unlink('public_html/img/base64img.png');
        }
    });});});
like image 166
Ben Muircroft Avatar answered Mar 25 '23 07:03

Ben Muircroft