1

Im using a service of microsoft graph to send an email with attachments. but when i sent the mail this dont have the attachments that i set to it. this is my Json that i generate

` message: {
            attachments: attachments[],
            subject: Email.Subject,
            body: {
              contentType: "HTML",
              content: Email.body
            },
            toRecipients: [
              {
                emailAddress: {
                  address: Email.To
                }
              }
            ],
          },
          saveToSentItems: true
}

theres my attachments array

0: {@odata.type: "#microsoft.graph.fileAttachment", contentBytes: "iVBORw0KGgoAAAANSUhEUgAAAPwA…JkiRJkiRJkiRJkiQZ4f8B1nomcWdNLuoAAAAASUVORK5CYII=", name: "outbound.png"}

1: {@odata.type: "#microsoft.graph.fileAttachment", contentBytes: "iVBORw0KGgoAAAANSUhEUgAAAQAA…eGOdrvC6af95tuTmRRrb4fxZWJvYuBoVJAAAAAElFTkSuQmCC", name: "inbound.png"}

`

and here is the way that i use the api of send mail

      sendMail: async function(accessToken, email) {

    const client = getAuthenticatedClient(accessToken);
    const sentResult = await client.api('/users/{tenantid}/sendMail').post(email);
}

the question is, the email is sent but why without the attachments

this is how i read my files

var attachments = [];
function addAttachments() {
allFiles.forEach(a => {
    let reader = new FileReader();
    reader.readAsDataURL(a);
    reader.onload = function() {
        attachments.push({
            '@odata.type': "#microsoft.graph.fileAttachment",
            name: a.name,
            contentType: a.type,
            contentBytes: reader.result.split(',')[1],
        });
    };
})}

here the console log of the object of email email_object

this is the result when i stringify the object

{"message":{"subject":"[AU1588259832480]-random subject","body":{"contentType":"HTML","content":"<p>body test</p>"},"toRecipients":[{"emailAddress":{"address":"email@test.com"}}],"internetMessageId":"AU1588259832480","attachments":[]}}

the attachmen object is emtpy but why?

Juan Saul
  • 11
  • 5

2 Answers2

0

You should not have the data:image/png;base64 preface to your contentBytes. That should just be the base64-encoded bytes from your image.

"attachments": [
    {
        "@odata.type": "#microsoft.graph.fileAttachment",
        "contentBytes": "/9j/4AAQSkZJRgABAQEAYAB...",
        "name": "outbound.png",
        "contentType": "image/png"
    }
]
Jason Johnston
  • 17,194
  • 2
  • 20
  • 34
  • there's a way to contact you? and see more closer my issue please – Juan Saul May 06 '20 at 17:49
  • You might want to just dump out your `email` object with `JSON.stringify(email)` before sending it. I suspect it isn't structured exactly right. Compare with the snippet I posted above. If you can't figure it out from that, it would be good to edit your post and include your code where you create your attachments array. – Jason Johnston May 06 '20 at 21:30
  • post updated, here the object strignify `{"message":{"subject":"[AU1588259832480]-random subject","body":{"contentType":"HTML","content":"

    body test

    "},"toRecipients":[{"emailAddress":{"address":"email@test.com"}}],"internetMessageId":"AU1588259832480","attachments":[]}}` attachments is empty but why, i make sure to push when i read the files
    – Juan Saul May 06 '20 at 23:26
  • Ok, this looks like more of a JavaScript error than a Graph problem. I believe your `onload` never gets called because you do `readAsDataURL` BEFORE you define your `onload` callback. – Jason Johnston May 07 '20 at 18:31
  • but as you see in the image that i post, when i console log the object the attachmets array has the files, but when i strignify the array disappear – Juan Saul May 07 '20 at 18:43
  • how can i fix it – Juan Saul May 07 '20 at 18:49
  • Without all of your code, there's no way to tell. If the attachments array inside your email object is empty, then of course Graph won't have any attachment to send. Given all of the callbacks involved, you could be passing your email object to your send function before the attachment array is even filled out. – Jason Johnston May 07 '20 at 19:09
  • there's a way to read a files that you suggest and fill that array inside the message object? – Juan Saul May 07 '20 at 19:20
  • it was my mistake of javascript, FileReader is async, so i was try to push the object while i read thats why the array was empty. now its working, thank you so much for you help – Juan Saul May 07 '20 at 22:27
0

here's how i solve the empty attachments, based on this post How to capture FileReader base64 as variable?

im new posting on stack overflow

  function getBase64(file, onLoadCallback) {
    return new Promise(function(resolve, reject) {
        var reader = new FileReader();
        reader.onload = function() { resolve(reader.result); };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

const Send = {
message: {
    subject: `[${quoteNumb ? quoteNumb : quoteHomeNumber}]-${Email.subject}`,
    body: {
        contentType: "HTML",
        content: Email.body
    },
    toRecipients: [],
    attachments: []
}};

async function sendMail() {

for (const a of allFiles) {
    var fileData = await getBase64(a).catch(err => {
        console.log(err)
    });
    Send.message.attachments.push({
        '@odata.type': "#microsoft.graph.fileAttachment",
        name: a.name,
        contentType: a.type,
        contentBytes: fileData.split(',')[1]
    });
}
graph.sendMail(AccesToken, Send);}
Juan Saul
  • 11
  • 5