Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MailMessage.To.Add() throwing exception : "An invalid character was found in the mail header: ','."

I am getting this error when I am using it in sharepoint project, while in console app its working fine

I am using MailMessage class to send email using SMTP . But when I trying to add user to 'To' property I am getting {"An invalid character was found in the mail header: ','."} exception, which I think something fishy is happening here as ',' is allowed to separate multiple users . Adding multiple user

** Multiple e-mail addresses must be separated with a comma character (",").**

MailMessage mailMessage = new MailMessage();

 mailMessage.To.Add("[email protected],[email protected],");
like image 564
nbi Avatar asked Sep 18 '14 08:09

nbi


3 Answers

Got the culprit: It's the extra comma(,) at the end of last email address

mailMessage.To.Add("[email protected],[email protected],");

Just removed that and voila! its working. Don't know why it's working in console application but not in sharepoint :(

mailMessage.To.Add("[email protected],[email protected]");

If this does not work in SharePoint then please add each address separately onto MailMessage object like below;

foreach (var address in StringofEmails.Split(",")) {
MailMessage.To.Add(new MailAddress(address.Trim(), ""));

}

like image 149
nbi Avatar answered Nov 04 '22 09:11

nbi


I got the error even though I don't have a comma at the end. It turns out that I need to leave a space after the comma

I have to change my code from a string.Join(",", emailList) to string.Join(", ", emailList)

Following didn't work for me.

mailMessage.To.Add("[email protected],[email protected]");

Following worked for me(Observe that there is space after the comma).

mailMessage.To.Add("[email protected], [email protected]");
like image 31
Thiru Avatar answered Nov 04 '22 10:11

Thiru


I can't replicate this. The above code works for me. Maybe try to add them using a seperate 'To' each time.

mailMessage.To.Add(x);
mailMessage.To.Add(y);
like image 2
Stephen Walker Avatar answered Nov 04 '22 08:11

Stephen Walker