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

I am using System.Net.Mail to send email in my application, but I have an exception and I cannot figure out what / where the problem is and how to fix it.

The problem is that I have an invalid char:

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

      

I have tried googling with no success.

Line with email address:

john@mydomain.org; beth@mydomain.org; alfred@mydomain.org; barbie@mydomain.org; 

      

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("vincent@mydomain.org", "admin");

    mailMessagePlainText.Subject = "test";
    mailMessagePlainText.Body = "test";

    mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), ""));
    mailMessagePlainText.Bcc.Add(new MailAddress("vincent@mydomain.org", ""));

    try
    {
        smtpClient.Send(mailMessagePlainText);
    }
    catch (Exception ex)
    {
        throw (ex);
    }

      

+3


source to share


3 answers


foreach (var address in List1.split(';')) {
    mailMessagePlainText.To.Add(new MailAddress(address.Trim(), ""));
}

      

Because according to your line above, each address in this loop above will produce the following:



"john@mydomain.org"
" beth@mydomain.org"
" alfred@mydomain.org"
" barbie@mydomain.org"

      

So by adding the .Trim () address to the address, your code will work.

+2


source


A MailAddressCollection

(yours for example mailMessagePlainText.To

) has a method Add

that takes a string containing a comma-separated list of mailing addresses.



To use this, you will need to change ;

to ,

and possibly remove any extra spaces.

+1


source


It looks like you are adding addresses as one MailAddress where you need to add them one at a time. I don't know what other overloads are available, but the following will probably work.

I split the line by ;

and added each address separately.

replace

mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), ""));

      

from

foreach (var address in List1.split(';')) {
    mailMessagePlainText.To.Add(new MailAddress(address , ""));
}

      

0


source







All Articles