Question

I have multiple email recipients stored in SQL Server. When I click send in the webpage it should send email to all recipients. I have separated emails using ;.

Following is the single recipient code.

MailMessage Msg = new MailMessage();
MailAddress fromMail = new MailAddress(fromEmail);
Msg.From = fromMail;
Msg.To.Add(new MailAddress(toEmail));

if (ccEmail != "" && bccEmail != "")
{
    Msg.CC.Add(new MailAddress(ccEmail));
    Msg.Bcc.Add(new MailAddress(bccEmail));
}

SmtpClient a = new SmtpClient("smtp server name");
a.Send(Msg);
sreader.Dispose();
Was it helpful?

Solution

Easy!

Just split the incoming address list on the ";" character, and add them to the mail message:

foreach (var address in addresses.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    mailMessage.To.Add(address);    
}

In this example, addresses contains "address1@example.com;address2@example.com".

OTHER TIPS

As suggested by Adam Miller in the comments, I'll add another solution.

The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:

MailMessage Msg = new MailMessage(fromMail, addresses);

In this particular case, we can replace the ';' for ',' and still make use of the constructor.

MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));

Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.

According to the Documentation :

MailMessage.To property - Returns MailAddressCollection that contains the list of recipients of this email message

Here MailAddressCollection has a in built method called

   public void Add(string addresses)

   1. Summary:
          Add a list of email addresses to the collection.

   2. Parameters:
          addresses: 
                *The email addresses to add to the System.Net.Mail.MailAddressCollection. Multiple
                *email addresses must be separated with a comma character (",").     

Therefore requirement in case of multiple recipients : Pass a string that contains email addresses separated by comma

In your case :

simply replace all the ; with ,

Msg.To.Add(toEmail.replace(";", ","));

For reference :

  1. https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=netframework-4.8
  2. https://www.geeksforgeeks.org/c-sharp-replace-method/

This is how it worked for me :

            var addresses = "firstemail@email.com;secondemail@email.com";
            var fromAddress = new MailAddress("sender@email.com", "Sender");
            const string fromPassword = "Password";
            string subject = "[Message] Message Subject" ;
            string body = "Message Body";

            var smtp = new SmtpClient
            {
                Host = "smtp.email.com", 
                Port = 587, //or 25 depending on your smtp server config
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            foreach (var address in addresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
            using (var message = new MailMessage(fromAddress.ToString(), address)
            {
                Subject = subject,
                Body = body,
                Priority = MailPriority.High
                
            })
                {
                
                    smtp.Send(message);
                }
            }

You can use LINQ:

string toEmail = "name1@mydomain.com;name1@mydomain.com";
toEmail.Split(";").ToList().ForEach(address => Msg.To.Add(new MailAddress(address)));

I've tested this using the following powershell script and using (,) between the addresses. It worked for me!

$EmailFrom = "<from@any.com>";
$EmailPassword = "<password>";
$EmailTo = "<to1@any.com>,<to2@any.com>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top