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.
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.
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);
}
}
Reviving this from the dead, if you separate the recipient email addresses by a comma, it will work.
this.Recipients = "email1@test.com, email2@test.com";
var mailMsg = new MailMessage(this.Sender, this.Recipients, this.Subject, this.Message);
SmtpClient smtpServer = new SmtpClient(SMTP);
smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpServer.Send(mailMsg);
Try this
string[] allTo = strTo.Split(';');
for (int i = 0; i < allTo.Length; i++)
{
if (allTo[i].Trim() != "")
message.To.Add(new MailAddress(allTo[i]));
}
private string FormatMultipleEmailAddresses(string emailAddresses)
{
var delimiters = new[] { ',', ';' };
var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
return string.Join(",", addresses);
}
Now you can use it like
var mailMessage = new MailMessage();
mailMessage.To.Add(FormatMultipleEmailAddresses("test@gmail.com;john@rediff.com,prashant@mail.com"));