Tuesday, 7 February 2012

Multiple addresses in MailMessage.To Property

Sending e-mail is easy with System.Net.Mail.MailMessage class. Unfortunately, MSDN example only shows how to send e-mail to one recipient. It is possible to send email to multiple recipients, but what is the delimiter?

From my tests I found out, that accepted delimiter is comma or comma-and-space. Semicolon without space will cause FormatException.
This small program will try sending e-mails with different delimiters. Let’s see what happens:
string from = "test@goleszympansy.pl";
string[] tos = {"one@goleszympansy.pl, two@goleszympansy.pl",
                "one@goleszympansy.pl,two@goleszympansy.pl",
                "one@goleszympansy.pl; two@goleszympansy.pl",
                "one@goleszympansy.pl;two@goleszympansy.pl"};
string subject = "Test mail";
string body = "GoleSzympansy";
string host = GetHost();

foreach (var to in tos)
{
    try
    {
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Host = host;
        MailMessage mailMessage = new MailMessage(from, to, subject, body);
        smtpClient.Send(mailMessage);
        Console.WriteLine("Mail send success: {0}", to);
    }
    catch
    {
        Console.WriteLine("Mail send failed: {0}", to);
    }
}
And this is a result:

So  at first it seemed, that semicolon-and-space would also be valid delimiter. But what would be actually be received?
In the third case ("one@goleszympansy.pl;  two@goleszympansy.pl"), the first part before space, together with semicolon, is considered to be recipient's name:

Summing up:
If you want to add more addresses, divide them by comma. And the space will divide display name and email address. The "To" property accepts following formats:
  • "email@server.com"
  • "email1@server1.com,  email2@server2.com"
  • "Name email@server.com"
  • "name email@server1.com, email@server2.com"
etc...

No comments:

Post a Comment