Guest Users To Send Email from SPFx Webpart.

Introduction

Hi friends, in this post I am going to share some of experience and alternates that I took to send email from SPFx web part for Guest Users.

I hope you all are aware of the Guest (external) users who can access SharePoint site and they can also be permitted to use the SharePoint Framework web part. You can refer to SPFx Webpart – External User Access | Knowledge Share (spknowledge.com) if you had any problem accessing the SPFx web part for the guest users. There are multiple ways in sending emails from SPFx using the default SharePoint methods or Graph API. Below are something you need to be aware when you are using SharePoint or MS Graph API to send email.

  • SharePoint API – If you use this API, emails can only be delivered within the domain users. It can be your own AD domain or domainname.onmicrosoft.com. You cannot use this API to send email outside of your domain like Gmail or Hotmail or Outlook.
  • MS Graph API – You can use this API to send emails to users who exists within your domain and also to external users like Gmail or Hotmail or Outlook. To do that you have to include webApiPermissionRequests in your package-solution.json file like the below.
"webApiPermissionRequests": [
      {
        "resource": "Microsoft Graph",
        "scope": "Mail.Send"
      }
    ]

The above APIs can be used directly within the SPFx web part for sending emails and below is the code to send email using the above APIs.

Note: I am using pnpjs for SharePoint APIs

Using SharePoint API

this._sp.utility.sendEmail(emailProps);

_sp is the SPFI and it has to be setup on the onInit event using the current context

emailProps is IEmailProperties which has the below properties

  • To – List of receivers represented by a string array. Mandatory
  • CC – List of receivers as CC represented by a string array. Optional
  • BCC – List of receivers as BCC represented by a string array. Optional
  • Subject – Email subject as string. Mandatory
  • Body – Email body as string and it can be a HTML string too. Mandatory
  • AdditionalHeaders – The additional headers appened to the request in key/value pairs. You have to use the content-type like emailProps.AdditionalHeaders = { “content-type”: “text/html” }; for sending HTML body. Optional
  • From – From address of the email as string. Optional

Using MS Graph API

You can send an email using Graph API using the below sample code

const messageProps = {
            message: {
                subject: emailProps.Subject,
                body: {
                    contentType: 'HTML',
                    content: emailProps.Body
                },
                toRecipients: emailProps.To,
                ccRecipients: emailProps.CC
            },
            saveToSentItems: true
        };
        const client = await graph.getClient("3");
        const isMailSent: boolean = await client.api('me/sendMail')
            .post(messageProps).then(() => true).catch(() => false);

graphMSGraphClientFactory object which you can derive from the current context like this.context.msGraphClientFactory

So far we have seen the different methods of sending an email using an internal user to both internal user and to the external user’s email like Gmail, Hotmail etc.

Trying to send email using Guest user

When the guest user try to send email using the above method, you might get an error like the below.

Payload

Response

Solution for Guest users to send email

Below are the 2 solutions that I had tried and it worked like charm.

Using Power Automate

You can use the Power Automate flow to send email whenever there is an item added to the list. Based on the metadata you can use the outlook actions to send email. I have used a SharePoint list called Emails and from the SPFx web part, when the users try to send an email, I added all the details like To, CC, Subject & Body to the list and configured the flow to trigger when an item is added or modified. I also have a field Status to maintain whether the email is sent successfully or not. Below is the list of actions used for sending email, you have to add a few actions to changed the Status field once the email is sent.

Using Azure Function

You can use the Azure Function with PnP Core SDK to send an email. Below are some of the guidelines that you can use to send an email and also shared the exact code to send an email.

  • You can directly send the params to the azure function and then use it to send an email
  • You can also use the list to add all the information and send the item id to the azure function. The function will grab all the information from the list and then will send an email.
  • In my case, its huge so I am using Azure Queue. I will be adding the item id to the queue and the queue trigger will use the HTTP trigger to send an email after fetching the items from the list.
var web = await ctx.Web.GetAsync(p => p.SiteUsers);
                    var testUser = web.SiteUsers.AsRequested().FirstOrDefault(p => p.LoginName.Contains("username"));
                    var graphUser = await testUser.AsGraphUserAsync();
                    await graphUser.SendMailAsync(mailOptions);

Below are few things that needs to be taken care while sending an email using PnPCore SDK and Graph API in Azure Function

  • Connecting to SharePoint and Graph API should be via Azure App and it should have mail.read graph permission which is delegated and not the application.
  • You have to use one of the domain users mailbox to send the email as a guest user. Better to create a service account with mailbox enabled. Whenever an email is sent, you can view the email in the mailbox sent items.

Reference Links

Getting started with the PnP Core SDK | PnP Core SDK

Azure Functions Overview | Microsoft Learn

Getting Started – PnP/PnPjs

Conclussion

I hope you had learned something new and I welcome your feedbacks and any other alternate approach to send an email as Guest users. More to come in future.

Leave a comment