Question

I have the following line of code to add a To address to a MailMessage instance. (The Xs in the string represent placeholders for alphabetic characters to prevent the identify of a customer.)

message.To.Add("Xxxxxxxxx Xxxxxx Xxxxxxxxxx, Xxx. <xxxxxx@xxxxxxxxx-xx.com>");

And I get the following error:

The specified string is not in the form required for an e-mail address

message is of type System.Net.Mail.MailMessage. My understanding was that this format was accepted. And, in fact, the code has been working with other addresses. Is it possible that the comma or period in the name is breaking the format?

EDIT

So here's what I have so far to construct the email address in the correct format.

// Construct a compound email address string
public static string BuildEmailAddress(string name, string emailAddress)
{
    if (String.IsNullOrWhiteSpace(name))
        return emailAddress;
    name = Regex.Replace(name, @"[()<>\[\]:;@\\,.""]",
        m => string.Format(@"\{0}", m.Value));
    return String.Format("\"{0}\" <{1}>", name, emailAddress);
}

Elements of this are still unclear. For example, if Yahoo encounters a comma, it simply wraps the name in double quotes and doesn't bother with the backslash. If anyone can say when the quotes are needed and when the backslash is needed, I'd welcome any suggestions.

Was it helpful?

Solution

I believe the comma isn't allowed, as it's technically a list separator in RFC 822/2822. At least, that's how I read it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top