Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse formatted email address into display name and email address?

Given the email address: "Jim" <[email protected]>

If I try to pass this to MailAddress I get the exception:

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

How do I parse this address into a display name (Jim) and email address ([email protected]) in C#?

EDIT: I'm looking for C# code to parse it.

EDIT2: I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string.

like image 260
Dylan Avatar asked Oct 02 '08 14:10

Dylan


3 Answers

If you are looking to parse the email address manually, you want to read RFC2822 (https://www.rfc-editor.org/rfc/rfc822.html#section-3.4). Section 3.4 talks about the address format.

But parsing email addresses correctly is not easy and MailAddress should be able to handle most scenarios.

According to the MSDN documentation for MailAddress:

http://msdn.microsoft.com/en-us/library/591bk9e8.aspx

It should be able to parse an address with a display name. They give "Tom Smith <[email protected]>" as an example. Maybe the quotes are the issue? If so, just strip the quotes out and use MailAddress to parse the rest.

string emailAddress = "\"Jim\" <[email protected]>";

MailAddress address = new MailAddress(emailAddress.Replace("\"", ""));

Manually parsing RFC2822 isn't worth the trouble if you can avoid it.

like image 153
Brannon Avatar answered Nov 03 '22 08:11

Brannon


Works for me:

string s = "\"Jim\" <[email protected]>";
System.Net.Mail.MailAddress a = new System.Net.Mail.MailAddress(s);
Debug.WriteLine("DisplayName:  " +  a.DisplayName);
Debug.WriteLine("Address:  " + a.Address);

The MailAddress class has a private method that parses an email address. Don't know how good it is, but I'd tend to use it rather than writing my own.

like image 39
Joe Avatar answered Nov 03 '22 09:11

Joe


Try:

"Jimbo <[email protected]>"
like image 2
Codewerks Avatar answered Nov 03 '22 07:11

Codewerks