0

I use the Microsoft Graph SDK to send an email without problem, but when I add an attachment, this attachment doesn't appear in the mail sent. the attachements here are of type "Blob". and in PDF format. I've gone through several stackoverflow questions corresponding to this issue, but none resolved my issue that is why I'm asking my question here.

    let graphMailAttachments = new Array<any>();

    //attachments is an array of blob
    attachments.forEach(async attachment => {
        let file = await new Response(attachment).arrayBuffer();

        graphMailAttachments.push({
            "contentBytes": file,
            "size": attachment.size,
            "@odata.type" : "#microsoft.graph.fileAttachment",
            "name": 'your-notes.pdf',
            "id" : this.newGuid(),
        }) 
    });

    subject = subject || "Your notes";
    body = body || "Your notes";

    let recipients = new Array<any>();
    to.forEach(receiver => {
        recipients.push({
            emailAddress:{
                address: receiver.email
            }
        })
    });

    let mail = {
        message: {
            subject: subject,
            body: {
                contentType: "Text",
                content: body,
            },
            toRecipients: recipients,
            attachments: graphMailAttachments,
        },
        SaveToSentItems : "true"
    }
    return this.graphClient.api('/me/sendMail').post(mail);

Am I doing something wrong ? The attachements just don't appear in the mail and it is kindof weird.

John Code
  • 655
  • 7
  • 24

2 Answers2

1

According to their samples, set the content type to application/pdf, then base64 encode the file bytes. Have you see the js sample code section?https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=javascript#request-3

rasharasha
  • 301
  • 3
  • 9
1

Before sending attachments via mail, You need to convert the attachment from arraybuffer to base64 string. I used the method below and it worked well for me:

arrayBufferToBase64( buffer ) : string {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return btoa( binary );
}

I got it from this stackoverflow answer:

John Code
  • 655
  • 7
  • 24