Blog

/
Triggering Out of Box User Invitations for a SharePoint Site Using SPFx and REST API
Published Date - 

Triggering Out of Box User Invitations for a SharePoint Site Using SPFx and REST API

 SharePoint Site Using SPFx and REST API

Managing permissions and user access in SharePoint is a critical aspect of site administration, especially when onboarding new users. SharePoint's REST API offers so many functionalities, including the ability to share files and send invitations. Here, in this blog, we will focus on how to use this API to add users to a SharePoint site and send them customized body invitations.

By using SharePoint Framework (SPFx) and the SharePoint REST API, you can automate this process, ensuring users are added to groups and send invitations link to the site. In this blog, we’ll walkthrough how to build a function in SPFx that adds users to a site group by their email, Azure Active Directory (AAD) ID, and SharePoint group ID, and sends a personalized email invitation automatically.

Step-by-Step Solution to Add Users and Send Invitations

We’ll break down the steps in implementing this functionality below,

1. Writing the Function to Send Email Invitations

Below is the code for the function that adds users to a SharePoint site's group and sends them an email invitation. It accepts parameters to specify the user’s email, Azure AD ID (aadId), and SharePoint group ID. The email content is predefined within the function.

public addUserAndSendInvitation = async (
  context: WebPartContext,
  userEmail: string,    // Email of the user
  groupId: string,      // SharePoint group ID to which the user will be added
  aadId: string         // Azure Active Directory (AAD) ID for the user
) => {
  // Get the current SharePoint site URL
  const siteUrl: string = context.pageContext.web.absoluteUrl;

  // API request URL to add the user and send the invitation
  const requestUrl = `${siteUrl}/_api/SP.Web.ShareObject`;

  // Construct People Picker input for the REST API request, including AAD ID
  const peoplePickerInput = [
    {
      Key: userEmail,
      IsResolved: true,
EntityData: { ObjectId: aadId },  // Include Azure AAD ID here
      PeopleType: "Person",
      PeopleSubtype: "OrganizationUser",
    },
  ];

  // Predefined email body content
  const emailBody = `
    Welcome to the SharePoint site!
      
    If you have any questions, feel free to reach out to our team.
  `;

  // Email properties including user role and invitation
  const emailProperties = {
    emailBody: emailBody,
    includeAnonymousLinkInEmail: false,  // Disable anonymous links in the invitation
    peoplePickerInput: JSON.stringify(peoplePickerInput),  // Serialize the people picker input
    roleValue: `group:${groupId}`,  // Add the user to the specified group ID
    sendEmail: true,  // Send the email invitation
    url: siteUrl,  // SharePoint site URL
    useSimplifiedRoles: true,  // Simplify the role assignment process
  };

  // HTTP request options for SPFx's spHttpClient
  const spHttpClientOptions: any = {
    headers: {
      Accept: "application/json;odata=nometadata",
      "Content-Type": "application/json;odata=nometadata",
      "odata-version": "",
    },
    body: JSON.stringify(emailProperties),
  };

  try {
    // Sending the POST request to SharePoint API
    const response: Response = await context.spHttpClient.post(
      requestUrl,
      SPHttpClient.configurations.v1,
      spHttpClientOptions
    );

    if (response.ok) {
      console.log("Email invitation sent successfully.");
    } else {
      const errorText = await response.text();
      console.error("Error sending email invitation:", errorText);
    }
  } catch (error) {
    console.error("Error sending email invitation:", error);
  }
};

2. Key Function Parameters Explained

This function accepts the following key parameters:

  • context: WebPartContext: Provides the context of the current SharePoint site or page. It’s used to obtain the site URL and to make HTTP requests using spHttpClient.
  • userEmail: string: The email address of the user you want to invite.
  • groupId: string: The SharePoint group ID to which the user will be added.
  • aadId: string: The unique Azure Active Directory (AAD) ID of the user, which ensures that the correct user is resolved in SharePoint, especially when email addresses or display names may not be unique.

3. How the Function Works

3.1 Constructing the API Request

The core part of this function is sending a POST request to SharePoint’s REST API endpoint /SP.Web.ShareObject, which handles sharing and adding users. The peoplePickerInput is where the user’s email and Azure AD ID are included, which helps SharePoint resolve the correct user.

const peoplePickerInput = [
  {
    Key: userEmail,
    IsResolved: true,
    EntityData: { ObjectId: aadId },  // Azure AD ID is included here
    PeopleType: "Person",
    PeopleSubtype: "OrganizationUser",
  },
];

3.2 Customizing the Invitation

The emailProperties object allows you to configure the content and behavior of the invitation. For instance, the roleValue field specifies the SharePoint group to which the user will be added by using groupId, and the emailBody is predefined to send a welcoming message to new users.

const emailProperties = {
  emailBody: emailBody,
  includeAnonymousLinkInEmail: false,
  peoplePickerInput: JSON.stringify(peoplePickerInput),
  roleValue: `group:${groupId}`,  // Specify the group by ID
  sendEmail: true,
  url: siteUrl,
  useSimplifiedRoles: true,
};

3.3 Sending the API Request

Once everything is configured, the function uses spHttpClient.post() to send the request to SharePoint. It handles both adding the user to the group and sending the email invitation.

const response: Response = await context.spHttpClient.post(
  requestUrl,
  SPHttpClient.configurations.v1,
  spHttpClientOptions
);

The response is checked for success, and any errors encountered during the process are logged.

4. Additional Improvements and Best Practices

Here are a few suggestions to further enhance the solution:

  • Dynamic GroupAssignment: Modify the groupId parameter to dynamically select different SharePoint groups based on the user's role or other conditions.
  • BulkInvitations: Extend the functionality to handle bulk user invitations by passing an array of emails and looping through them.
  • Automation with Power Automate: Further automate this API using Power Automate, enabling seamless integration with SharePoint workflows.

Conclusion

The process of adding users to SharePoint groups and sending personalized invitations using SPFx and the SharePoint RESTAPI can significantly streamline your SharePoint site management tasks. It saves time, improves the user onboarding experience, and ensures consistency.

Moreover, by integrating this solution with Power Automate, you can trigger these invitations automatically based on specific events or workflows, making the process even more efficient.

Stay tuned for future blogs where we'll explore more ways to automate and enhance SharePoint site management!

No items found.

faqS

No items found.
Call-icon

Contact us

How can we help you?

Thank you!

We will get back to you in one business day.
If this is urgent, Please schedule a time
Oops! Something went wrong while submitting the form.
Linked-in
Contact-us