Create your own custom-themed FREE INTRANET DESIGN IN A MINUTE! Try it Yourself!
Do it Yourself Intranet Design
Logo
Phone
  • About
  • Solutions
    SOP & Policies ManagerDocument Management SystemKnowledge Management SystemEmployee Onboarding SolutionPerformance ManagementProject ManagementProcess MiningIntranet for Small Businesses
  • Services
    IntranetSharePoint
    UIUX Services
    SharePoint Design Services
    Power Platform
    Power PagesPower AutomatePower AppsPower BI (MS Fabric)
    Copilot StudioAI AgentsMicrosoft Teams Apps
  • Templates
  • LookBook
    Modern SharePoint WebpartsBirthday Reminder WebpartWeather Webpart
  • Case studies
    SharePoint Services
    Microsoft Teams
    Microsoft 365
    Microsoft Power Platform
    Power Apps
    Power Automate
    Power Pages
    Azure Functions
  • Blog
    SharePoint Services
    Microsoft Teams
    Microsoft 365
    Microsoft Power Platform
    Power Apps
    Power Automate
    Power Pages
    Azure Functions
    Copilot
    Design
    Power BI (MS Fabric)
    Artificial Intelligence(AI)
    Microsoft Viva
  • Partners
  • Careers
Schedule a call
Schedule a demo
Blog
/
Triggering Out of Box User Invitations for a SharePoint Site Using SPFx and REST API
Published Date - 
Eulin Bennet
Eulin Bennet
February 10, 2025

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

 SharePoint Site Using SPFx and REST API
SharePoint Services

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 Group Assignment: Modify the groupId parameter to dynamically select different SharePoint groups based on the user's role or other conditions.
  • Bulk Invitations: 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!

Basic Template5
Basic Template4
Basic Template3
Basic Template2
Basic Template1
OOTB Template
Consumer Electronics Template
Healthcare Template 2
Real-Estate Template 1
Real-Estate Template 4
Transport Template 1
Environment sustainability Template 1
Environment sustainability Template 4
Digital Media Template 3
Digital Media Template 4
Digital Media Template 2
No items found.

faqS

No items found.
Call-icon

Contact us

How can we help you?
Urgent? Book a time

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.

Subscribe to our Newsletter

Linked-In
Subscribe
Back to all blogs
Related blog
sharepoint-migration
SharePoint Services

How to Migrate to SharePoint Without Downtime Best Practices & Expert Advice

May 30, 2025

Migrating to SharePoint can unlock a range of benefits for your organization from improved collaboration and document management to tighter integration with Microsoft 365.

Nivetha Janagaraj
Nivetha Janagaraj
sharepoint-webparts-modern-intranet
SharePoint Services

Web Parts That Make Your SharePoint Intranet Feel Like a Website

May 30, 2025

Intranets often get a bad reputation. They're seen as clunky, outdated platforms that employees avoid unless absolutely necessary.

Nivetha Janagaraj
Nivetha Janagaraj
psychology-decision-making-in-ux
SharePoint Services

The Science Behind the Click: The Psychology of Decision-Making!

May 29, 2025

All three of them are known for wearing almost the same outfit every day, inadvertently creating their own personal brand.

Johnsi Jayasingh
Johnsi Jayasingh
k
Phone
Phone number
+91 98841 89463
+1 737 289 0434
Mail
E-mail
sales@sharepointdesigns.com
Business-Hours
Business-Hours
24/7
Clutch: Microsoft ECM Company 2023Clutch: Microsoft ECM Company 2023

SharePoint Designs is a leading provider of Microsoft ecosystem services – covering apps, intranets, and other digital gateways. We offer out-of-the-box SharePoint development, implementation, migration, and maintenance solutions to build or increase business resilience, operational excellence, and employee productivity. Some of our SharePoint services are Microsoft SharePoint configuration, Microsoft Teams set-up, advanced document management, and streamlined external sharing.

SharePoint Designs’ expertise unlocks the value of Microsoft Power Apps and Power Automate. We help quickly develop and deploy desktop/mobile applications and multi-layered automated workflows. SharePoint Designs also delivers cost-effective Copilot studio services to bridge conversational gaps between employers and customers.

Our suite proficiency makes it effortless to design, manage, and monitor custom-built AI-driven chatbots that are catered to specific organizational use cases. SharePoint Designs is backed by a track record of friction-free integration and smooth deployment for multiple clients across the world. Our flexible pricing plans can meet the unpredictable demands of your business. We also provide 24/7 customer support at global and regional levels.

LookbookModern SharePoint WebpartsBirthday Reminder WebpartWeather Webpartaboutcareers
Privacy PolicyTerms of use
Contact us
Solution
Document ManagementKnowledge ManagementEmployee OnboardingPerformance ManagementProject ManagementIntranet for Small Businesses
servicesIntranetsharePointSharePoint Design Servicesmicrosoft teams AppsPower PagesPower PlatformPower AppsPower automatePower BI (MS Fabric)Copilot StudioAI Agents
case studies
SharePoint Services
Microsoft Teams
Microsoft 365
Microsoft Power Platform
Power Apps
Power Automate
Power Pages
Azure Functions
blogsharePoint ServicesMicrosoft teamsMicrosoft 365Microsoft Power PlatformPower Appspower automatepower pagesazure functions
Lookbook
Modern SharePoint WebpartsBirthday Reminder WebpartWeather Webpart
About
Solution
Document ManagementKnowledge ManagementEmployee OnboardingPerformance ManagementProject ManagementIntranet for Small Businesses
services
IntranetSharePointSharePoint Design ServicesMicrosoft Teams AppsPower PagePower PlatformPower AppsPower AutomateCopilot StudioAI AgentsPower BI (MS Fabric)
case studies
Power Pages
Azure Functions
Power Automate
Power Apps
SharePoint Services
Microsoft Teams
Microsoft 365
Microsoft Power Platform
blog
Copilot
Design
Power BI (MS Fabric)
Artificial Intelligence(AI)
Microsoft Viva
Azure Functions
Power Pages
Power Automate
Power Apps
Microsoft Teams
SharePoint Services
Microsoft 365
Microsoft Power Platform
careers
Link 1Link 2Link 3
CareersPrivacy PolicyTerms of use
CONTACT US
SharePoint Designs © 2025 All Rights Reserved.
facebook-logoLinkedIn-logotwitter-logo
Ask Alfred