How to add user(s) to distribution list group in Office 365 using C#?

Brass Contributor

I am creating one distribution list for Unsubscriber and dynamically wants to add external user(s) to that group so in the future no email goes to those users. How to do with programming c#? Please help me out with sample code. 

3 Replies

@itsmesri 

 

You can't use Microsoft Graph API or Azure AD Graph to add members in a Distribution Group. So the easiest way is, add member using the Exchange Online Powershell cmdlet Add-DistributionGroupMember

 

You can refer this post to connect Exchange Online Powershell module and run commands in C#.

@Kevin Morgan 

 

I tried using sample code that you gave me. But command fails to me. Any suggestions?

 

string connectionUri = "<a href="<a href="https://outlook.office365.com/powershell-liveid/" target="_blank">https://outlook.office365.com/powershell-liveid/</a>" target="_blank"><a href="https://outlook.office365.com/powershell-liveid/</a" target="_blank">https://outlook.office365.com/powershell-liveid/</a</a>>";
string loginPassword = ConfigurationManager.AppSettings["PWD"].ToString();
string loginUser = ConfigurationManager.AppSettings["UID"].ToString();
SecureString secpassword = new SecureString();
foreach (char c in loginPassword)
{
secpassword.AppendChar(c);
}
PSCredential credential = new PSCredential(loginUser, secpassword);
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri(connectionUri));
command.AddParameter("Credential", credential);
command.AddParameter("Authentication", "Basic");
powershell.Commands = command;

runspace.Open();
powershell.Runspace = runspace;
Collection<System.Management.Automation.PSObject> result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
{
throw new Exception("Fail to establish the connection");
}

powershell = PowerShell.Create();
command = new PSCommand();
command.AddCommand("Invoke-Command");
string DLGroupName = "UnsubscribersList";
command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("Add-DistributionGroupMember -Identity " + DLGroupName + " -Member " + txtEmail.Text));
command.AddParameter("Session", result[0]);
powershell.Commands = command;
powershell.Runspace = runspace;
result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
{
throw new Exception("Command failed");
}

 

I am getting this error while running Add-DistributionGroupMember command

 

{Couldn't find object "test11@gmail.com". Please make sure that it was spelled correctly or specify a different object.}

 

 

UPDATE:

 

I tried add email address to contacts then adding to distribution List still get an error.

 using (powershell = PowerShell.Create())
            {
                command = new PSCommand();
                command.AddCommand("Invoke-Command");

                command.AddParameter("ScriptBlock",
                    System.Management.Automation.ScriptBlock.Create(
                        "New-MailContact -Name '" + txtEmail.Text + "' -ExternalEmailAddress '" + txtEmail.Text + "'"));
                command.AddParameter("Session", result[0]);
                powershell.Commands = command;
                powershell.Runspace = runspace;
                result = powershell.Invoke();
                if (powershell.Streams.Error.Count > 0 || result.Count != 1)
                {
                    throw new Exception("Fail to establish the connection");
                }
            }

            using (powershell = PowerShell.Create())
            {
                command = new PSCommand();
                command.AddCommand("Invoke-Command");
                string DLGroupName = "UnsubscribersList";
                command.AddParameter("ScriptBlock",
                    System.Management.Automation.ScriptBlock.Create(
                        "Add-DistributionGroupMember -Identity '" + DLGroupName + "' -Member " + txtEmail.Text + ""));
                command.AddParameter("Session", result[0]);
                powershell.Commands = command;
                powershell.Runspace = runspace;
                result = powershell.Invoke();
                if (powershell.Streams.Error.Count > 0 || result.Count != 1)
                {
                    throw new Exception("Fail to establish the connection");
                }
            }

Error

Cannot convert the "test11@gmail.com" value of type "Deserialized.Microsoft.Exchange.Data.Directory.Management.MailContact" to type "System.Management.Automation.Runspaces.PSSession".

 

@itsmesri 

 

You are facing problem with below line :

command.AddParameter("Session", result[0]);

You have to store New-PSSession result (result[0]) in another variable and use it for subsequent calls.

var session = result[0];// New-PSSession result
// In subsequent calls, use it as below line.
command.AddParameter("Session", session);

My complete working script :

string connectionUri = "<a href="https://outlook.office365.com/powershell-liveid/" target="_blank">https://outlook.office365.com/powershell-liveid/</a>";
string loginUser = ConfigurationManager.AppSettings["UID"].ToString();
string loginPassword = ConfigurationManager.AppSettings["PWD"].ToString();
SecureString secpassword = new SecureString();
foreach (char c in loginPassword)
{
    secpassword.AppendChar(c);
}
PSCredential credential = new PSCredential(loginUser, secpassword);
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri(connectionUri));
command.AddParameter("Credential", credential);
command.AddParameter("Authentication", "Basic");
powershell.Commands = command;

runspace.Open();
powershell.Runspace = runspace;
Collection<System.Management.Automation.PSObject> result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
{
    throw new Exception("Fail to establish the connection");
}

var session = result[0];

//string ExtEmail = "Test1@gmail.com";
string ExtEmail = txtEmail.Text;
using (powershell = PowerShell.Create())
{
    command = new PSCommand();
    command.AddCommand("Invoke-Command");

    command.AddParameter("ScriptBlock",
        System.Management.Automation.ScriptBlock.Create(
            "New-MailContact -Name '" + ExtEmail + "' -ExternalEmailAddress '" + ExtEmail + "'"));
    command.AddParameter("Session", session);
    powershell.Commands = command;
    powershell.Runspace = runspace;
    result = powershell.Invoke();
    if (powershell.Streams.Error.Count > 0 || result.Count != 1)
    {
        //throw new Exception("Fail command");
    }
}

using (powershell = PowerShell.Create())
{
    command = new PSCommand();
    command.AddCommand("Invoke-Command");
    string DLGroupName = "UnsubscribersList";
    command.AddParameter("ScriptBlock",
        System.Management.Automation.ScriptBlock.Create(
            "Add-DistributionGroupMember -Identity '" + DLGroupName + "' -Member " + ExtEmail + ""));
    command.AddParameter("Session", session);
    powershell.Commands = command;
    powershell.Runspace = runspace;
    result = powershell.Invoke();
    if (powershell.Streams.Error.Count > 0 )
    {
        throw new Exception("Fail command");
    }
}