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.
We’ll break down the steps in implementing this functionality below,
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);
}
};
This function accepts the following key parameters:
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",
},
];
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,
};
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.
Here are a few suggestions to further enhance the solution:
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!