yash dogra
yash dogra

Reputation: 99

file attachment using microsoft graph send mail not working

Getting the mail without the attachment I am using microsoft graph sendMail. I need to add an attachment at the same time. I added the attachment Object inside message of request body. But received the mail without the attaachment. i was following : https://learn.microsoft.com/en-us/graph/api/resources/fileattachment?view=graph-rest-1.0 PFB my code.

function sendAttachment(accessToken) {
  const attachments = [
    {
      "@odata.type": "#microsoft.graph.fileAttachment",
      "contentBytes": "",
      "name": "example.jpg"
    }
  ];
  var message= 
      { subject: 'It\'s working ',
        body: 
         { contentType: 'Text',
           content: 'Sending mail using microsoft graph and Outh2.0' },
        toRecipients: [ { emailAddress: { address: '' } } ],
        ccRecipients: [ { emailAddress: { address: '' } } ] 
      };

  message["attachments"] = attachments;

  var options = { 
  method: 'POST',
  url: 'https://graph.microsoft.com/v1.0/users/[email protected]/sendMail',
  headers: 
   { 'Cache-Control': 'no-cache',
     Authorization: 'Bearer '+ accessToken,
     'Content-Type': 'application/json' },
  body:JSON.stringify({
      "message": message, 
      "SaveToSentItems": "false"
    }),
  json: true
   };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log("--attachment--");
});
}

what am i missing here ??

Upvotes: 0

Views: 1134

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59358

It most likely occurs due to invalid payload request, from request documentation

body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.

So, either json option should be omitted:

const options = {
    method: "POST",
    url: `https://graph.microsoft.com/v1.0/users/${from}/sendMail`,
    headers: {
      "Cache-Control": "no-cache",
      Authorization: "Bearer " + accessToken,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      message: message,
      SaveToSentItems: "true"
    })
  };

or json set to true but body specified as JSON object:

const options = {
    method: "POST",
    url: `https://graph.microsoft.com/v1.0/users/${from}/sendMail`,
    headers: {
      "Cache-Control": "no-cache",
      Authorization: "Bearer " + accessToken,
      "Content-Type": "application/json"
    },
    body: {
      message: message,
      SaveToSentItems: "true"
    },
    json: true
  };

Upvotes: 0

Related Questions