Reputation: 1407
I'm using System.Net.Mail
to send email in my application but I get an exception and I can't figure out what/where the problem is and how to fix it.
The error says I have some invalid char:
An invalid character was found in the mail header: ';'.
I tried google without success.
The string with email address is:
[email protected]; [email protected]; [email protected]; [email protected];
Here is my email sending code:
SmtpClient smtpClient = new SmtpClient("smtp.........");
System.Net.Mail.MailMessage mailMessagePlainText = new System.Net.Mail.MailMessage();
mailMessagePlainText.IsBodyHtml = true;
mailMessagePlainText.From = new MailAddress("[email protected]", "admin");
mailMessagePlainText.Subject = "test";
mailMessagePlainText.Body = "test";
mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), ""));
mailMessagePlainText.Bcc.Add(new MailAddress("[email protected]", ""));
try
{
smtpClient.Send(mailMessagePlainText);
}
catch (Exception ex)
{
throw (ex);
}
Upvotes: 10
Views: 35956
Reputation: 938
foreach (var address in List1.split(';')) {
mailMessagePlainText.To.Add(new MailAddress(address.Trim(), ""));
}
Because according to your string here above, each address in this loop above would produce following:
"[email protected]"
" [email protected]"
" [email protected]"
" [email protected]"
So by adding .Trim()
to address would make your code work.
Upvotes: 10
Reputation: 39283
A MailAddressCollection
(like your mailMessagePlainText.To
) has an Add
method that accepts a string containing a list of mail addresses, separated by a comma.
So to use that, you will need to change the ;
into a ,
and possibly remove the extra spaces.
Upvotes: 2
Reputation: 3305
It looks like you're adding the addresses as a single MailAddress, where you need to add them 1 at a time. I don't know what other overloads are available, but the following will probably work.
I split the string by ;
and add each address separately.
replace
mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), ""));
with
foreach (var address in List1.split(';')) {
mailMessagePlainText.To.Add(new MailAddress(address , ""));
}
Upvotes: 1