Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix exception thrown when sending mail message to multiple recipients?

Tags:

c#

email

.net-4.0

In the code snippet below, I'm getting a FormatException on 'this.Recipients'. More specifically, the message is "An invalid character was found in the mail header: ';'".

Recipients is a string of three email addresses separated by semicolons (the ';' character). The list of recipients is read from an app.config and the data is making it into the Recipients variable.

How can I be getting this error when multiple recipients should be separated by a semicolon? Any suggestions? As always, thanks for your help!

public bool Send()
{
    MailMessage mailMsg = 
       new MailMessage(this.Sender, this.Recipients, this.Subject, this.Message);

    SmtpClient smtpServer = new SmtpClient(SMTP);
    smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;

Edit #1 - This says use a semicolon.

like image 334
DenaliHardtail Avatar asked May 06 '11 16:05

DenaliHardtail


3 Answers

I can't see anything in the MailMessage constructor documentation to suggest you can specify multiple recipients like that. I suggest you create the MailMessage object and then add each email address separately.

Note that the MailAddressCollection.Add method is documented to accept comma-separated addresses... so it's possible that that would work in the constructor too.

like image 147
Jon Skeet Avatar answered Oct 22 '22 03:10

Jon Skeet


You have to use the .Add method to add these addresses. Here is some sample code that I use:

string[] toAddressList = toAddress.Split(';');

//Loads the To address field
foreach (string address in toAddressList)
{
    if (address.Length > 0)
    {
        mail.To.Add(address);
    }
}
like image 5
IAmTimCorey Avatar answered Oct 22 '22 04:10

IAmTimCorey


Reviving this from the dead, if you separate the recipient email addresses by a comma, it will work.

this.Recipients = "[email protected], [email protected]";

var mailMsg = new MailMessage(this.Sender, this.Recipients, this.Subject, this.Message);
SmtpClient smtpServer = new SmtpClient(SMTP);
smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpServer.Send(mailMsg);
like image 2
clyc Avatar answered Oct 22 '22 04:10

clyc