0

I am adding members to a group with the code below.

My question is very simple :

When adding members with this code, the invited person does not get an email notifying them. However when doing the same from the UI there is an option to notify the user. How can I do that from the code?

public void UpdateGoupMembers(string groupName, List<string> loginNames)
{
    using (var clientContext = new ClientContext(baseUrl))
    {
        clientContext.Credentials = credentials;
        var web = clientContext.Web;

        var group = web.SiteGroups.GetByName(groupName);

        if (group != null)
        {
            foreach (var loginName in loginNames)
            {
                var user = web.EnsureUser(loginName);

                if (user != null)
                {
                    group.Users.AddUser(user);
                }
            }

            var existingUsers = group.Users;

            clientContext.Load(existingUsers, includes => includes.Include(
                f => f.LoginName,
                f => f.UserId,
                f => f.PrincipalType,
                f => f.Email,
                f => f.Id));

            clientContext.ExecuteQuery();

            foreach (var existingUser in existingUsers)
            {
                var userName = existingUser.LoginName.Split('|')[2];
                if (!loginNames.Contains(userName))
                {
                    group.Users.RemoveByLoginName(existingUser.LoginName);
                }
            }
        }

        clientContext.ExecuteQuery();
    }
}
1

Yes, ability to send Welcome mail is not available OOTB when adding a user to a group programatically . However, you can use the Utility.SendEmail method of Microsoft.SharePoint.Client.Utilities namespace to send the mail.

Try and modify the below sample code:

var user = web.EnsureUser(loginName);

if (user != null)
{
    group.Users.AddUser(user);
}

var emailProperties = new EmailProperties();
// Email address of user
emailProperties.To = new string[] { user.Email };

emailProperties.Body = "<html><body><h3>Welcome to the group</h3><p>This is some welcome text</p>";
emailProperties.Subject = "Added to group";
Utility.SendEmail(clientContext, emailProperties);

clientContext.ExecuteQuery();

Reference - Utility SendEmail method

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.