Reputation: 1386
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],");
Upvotes: 34
Views: 64960
Reputation: 1
you can do something like this as well. This approach also validates the email address before adding it to the dl list. So you will only valid dl list.
var emails = ("[email protected],[email protected],").Split(',');
MailMessage mailMessage = new MailMessage();
foreach (var email in emails)
{
var emailAddressAttribute = new EmailAddressAttribute();
if(emailAddressAttribute.IsValid(email))
{
MailMessage.To.Add(email);
}
}
Upvotes: -1
Reputation: 1386
Got the culprit: It's the extra comma(,) at the end of last email address
mailMessage.To.Add("[email protected],[email protected],");
Remove the trailing comma and it will work:
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(), ""));
}
Upvotes: 53
Reputation: 417
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]");
Upvotes: 14
Reputation: 20401
I had to update a project with nicer looking emails and I published the web project and got this error.
Mine was from some debug code in which
currentUser = [email protected]
got added
MailAddress mailAddressUser = new MailAddress(currentUser + "@mycompany.com");
Essentially:
[email protected]@mycompany.com
So instead of an issue with a trailing comma, literally another @
Upvotes: -1
Reputation: 574
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);
Upvotes: 2