2

"code for sending email above is the code .iam tired of scratching my head but still not able to see the image in the mail. I am converting the image into base 64 encoded string and also following the sendgrid syntax still not able to send the image .i dunno wats going wrong here.:"

var app = require("../../../server/server");
var base64Img = require("base64-img");

let status = null;
let textBody,
  htmBody = null;
var DataSource = require("loopback-datasource-juggler").DataSource;
var dsSendGrid = new DataSource("loopback-connector-sendgrid", {
  api_key: app.customConfig.mail.sendgrid.api_key
});

var fs = require("fs");

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

function base64_decode(base64str, file) {
  var bitmap = new Buffer(base64str, "base64");
  fs.writeFileSync(file, bitmap);
  console.log(
    "******** File created from base64 encoded string ********",
    base64str
  );
}

var base64str = base64_encode("../../../images/Campaign-images/Christmas.png");

let message = {
  to: "somebody@gmail.com",
  from: "noreply@gmail.com",
  subject: "test",
  text: "hi",
  html: '<img src="cid:myimagecid"/>',
  attachment: [
    {
      filename: "Christmas2.png",
      content: base64str,
      ContentId: "myimagecid"
    }
  ]
};
console.log(message);
app.models.Email.send(message)
  .then(result => {
    return "sent";
  })
  .catch(err => {
    console.log(err);

    return "failed";
  });
libik
  • 22,239
  • 9
  • 44
  • 87
rosh
  • 97
  • 3
  • 13

3 Answers3

2

This code will work for sure

//imageData= "data:image/png;base64,ine793nfdsf......."

imageb64 = imageData.replace('data:image/png;base64,' , ''); 
//remove data:image/png;base64,            

const msg = {
            to: 'example@gmail.com',
            from: 'test@gmail.com',
            subject: "image attached",
            html :'<img src="cid:myimagecid"/>',
            attachments: [
              {
                filename: "imageattachment.png",
                content: imageb64,
                content_id: "myimagecid",
              }
            ]
          };

      sgMail.send(msg);
D C
  • 708
  • 1
  • 6
  • 17
1

If I look to the https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html

I see it is attachments not attachment

Also there is content_id instead of ContentId

Also make sure, you are using right version (I am pointing to v3 but I think you can choose to use v2)

libik
  • 22,239
  • 9
  • 44
  • 87
  • 1
    thanks a lot it worked. can you help me with showing the image in the message body and not as a separate attachment – rosh Dec 05 '17 at 15:50
  • Sorry, I did not do that, but I know that you have to send it as HTML instead of TEXT and use img src. – libik Dec 06 '17 at 08:54
0

May be it is because of your mail client doesn't support for base 64 encoded images see this question

user3014595
  • 124
  • 9