Search code examples
javascriptreactjsmicrosoft-graph-apimicrosoft-graph-mailmicrosoft-graph-files

Microsoft graph send email with attachments


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 protected]"}}],"internetMessageId":"AU1588259832480","attachments":[]}}

the attachmen object is emtpy but why?


Solution

  • 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);}