How to send an email using Graph API with attachments in SPFx WebPart

Ahamed Fazil Buhari
 
Senior Developer
April 11, 2020
 
Rate this article
 
Views
2948

If we want to send an email from user own account then using Graph API will be handy. Below you can find the script that’s been used in SPFx webpart to send an email on user behalf.

Created SPFx webpart with below settings.

spfx

spfx

The main function which take care of sending an email is given below, referred from MS docs link

public sendMailSPPals = async (emailContent: IGraphEmailProps
    ): Promise<boolean> => {
        let emailAttachments = emailContent.attachments.map(attach => {
            if (!attach.isRemove) {
                return {
                    "@odata.type": "#microsoft.graph.fileAttachment",
                    name: attach.name,
                    contentBytes: attach.rawData.split("base64,")[1]
                };
            }
        });
        emailAttachments = emailAttachments.filter(emAt => emAt !== undefined);

        const emailprops = {
            message: {
                subject: emailContent.subject,
                body: {
                    contentType: "Text",
                    content: emailContent.body
                },
                toRecipients: [
                    {
                        emailAddress: {
                            address: emailContent.toEmailAddress
                        }
                    }
                ],
                attachments: emailAttachments
            },
            saveToSentItems: false
        };
        try {
            const client = await this.msGraphClientFactory.getClient();
            const isMailSent: boolean = await client.api('me/sendMail')
                .version("v1.0")
                .post(emailprops).then(() => true).catch(() => false);
            return isMailSent;
        }
        catch (e) {
            console.error("Error while sending email" + e.message);
            return false;
        }
    }

The whole solution is available in the GitHub repo

Important

Before we make this me/sendMail workable we should approve API access for Mail.Send in SharePoint Admin center. To achieve that we can use PnP powershell to request for “Mail.Send” scope.

pnp

Approve the API access for Mail.Send

sp admin

Make sure it is approved

approved

This simple webpart looks like below where user can fill, attach an attachment and send

webpart

After click on Send Mail it will take trigger send.mail Graph API. Below you can see the email that has been triggered to myself since I use To address as my own email address.

mailbox

Happy Coding

Fazil

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment