How to send Email to Multiple Recipients in .Net 2.0 Using System.Net.Mail?

Problem:

Recently I had to deal with a scenario in which I had written a custom C# class to send email Notifications. The class used the .Net Framework in built Namespace System.Net.Mail

What I noticed was, when I sent an email to a single recipient i.e either a single individual recipient or a single group it worked fine, but when I tried to assign more than one recipient separated by a semicolon ‘;’ it caused an error stating “An Invalid character was found in the mail header

This is the code:

       string from = "FromEmailID@gmail.com";

string to = "emailid1@gmail.com;emailid2@gmail.com";

       MailMessage message = new MailMessage(from, to);

            message.IsBodyHtml = true;

            message.Subject = "This is the Email Subject";

            message.Body = “This is the Email Content”;

            SmtpClient client = new SmtpClient();

            client.Host = smtpHost;

 

 

Solution:

Method 1:

One way of solving the above problem is easy and simple. It appears that the To property of the MailMessage class accepted semicolon “;” as the separator for multiple email recipients in .Net 1.0 but it does not in .Net 2.0 or above. So instead of using semicolon “;” as the separator for multiple recipients in the To property of the MailMessage if you use comma “,” it seems to work fine without any error. So if you change the above code as shown below it should work fine. The  code change is highlighted below.

       string from = "FromEmailID@gmail.com";

string to = "emailid1@gmail.com,emailid2@gmail.com";

       MailMessage message = new MailMessage(from, to);

 

            message.IsBodyHtml = true;

            message.Subject = "This is the Email Subject";

            message.Body = “This is the Email Content”;

            SmtpClient client = new SmtpClient();

            client.Host = smtpHost;

 

Method 2:

The other method to add multiple recipients is as follows:

            MailMessage message2 = new MailMessage();

            message2.To.Add("emailid1@gmail.com");

            message2.To.Add("emailId2@gmail.com");

            message2.To.Add("emailId3@gmail.com");

 

            message.IsBodyHtml = true;

            message.Subject = "This is the Email Subject";

            message.Body = “This is the Email Content”;

            SmtpClient client = new SmtpClient();

            client.Host = smtpHost;

Hope that was helpful.

Have a Nice Day

Robert

Tags: