Tuesday, 27 September 2016

Invite external users to SharePoint site using CSOM

We may required to automate the process of inviting external users to SharePoint site or document. In this article, I am going write CSOM based C# code to send invitation for bulk external users to site or document.

The Microsoft SharePoint Online SDK assembly Microsoft.SharePoint.Client.dll includes the namespace Microsoft.SharePoint.Client.Sharing in which there are two useful classes called WebSharingManager and DocumentSharingManager. We can use the class WebSharingManager to share a SharePoint site with external users.
private static void InviteExternalUsersForSite() 
    // Create Connection to SharePoint Online Site 
    using (var context = new ClientContext("https://spotenant.sharepoint.com/sites/contosobeta")) 
        context.Credentials = new SharePointOnlineCredentials("admin@spotenant.com", securePwd); 
        // Create invitation request list to multiple users 
        var users = new List<string>() { "admin@extDomain.com", "alexd@extDomain.com"}; 
        var userRoles = new List<UserRoleAssignment>(); 
        foreach (var user in users) 
            UserRoleAssignment role = new UserRoleAssignment(); 
            role.UserId = user; 
            role.Role = Role.View; 
        string message = "Please accept this invite to access our SharePoint Site."; 
        // Send invitation requests to external users 
        WebSharingManager.UpdateWebSharingInformation(context, context.Web, userRoles, true, message, true, true); 
We need to use the class DocumentSharingManager to programmtically share a document with external users.
string absoluteFileUrl = "https://spotenant.sharepoint.com/sites/contosobeta/Shared%20Documents/Document.docx"; 
DocumentSharingManager.UpdateDocumentSharingInfo(context, absoluteFileUrl, userRoles, true, true, true, customMsg, true, true);
Note: Here, I have used list to send invitation for multiple users, but you can alternatively import users from csv file and share site or document with bulk users.


No comments:

Post a Comment