Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An invalid character was found in the mail header: ';' in c#

Tags:

c#

email

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);
    }
like image 302
Antonio Mailtraq Avatar asked Jul 01 '15 07:07

Antonio Mailtraq


1 Answers

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.

like image 102
Lucas Reppe Welander Avatar answered Nov 05 '22 05:11

Lucas Reppe Welander