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.
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.
Approve the API access for Mail.Send
Make sure it is approved
This simple webpart looks like below where user can fill, attach an attachment and send
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.
Happy Coding
Fazil
Leave a comment