如何将格式化的电子邮件地址解析为显示名称和电子邮件地址? [英] How to parse formatted email address into display name and email address?

查看:80
本文介绍了如何将格式化的电子邮件地址解析为显示名称和电子邮件地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定电子邮件地址:Jim"

Given the email address: "Jim" <jim@example.com>

如果我尝试将其传递给 MailAddress,则会出现异常:

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.

如何在 C# 中将此地址解析为显示名称 (Jim) 和电子邮件地址 (jim@example.com)?

How do I parse this address into a display name (Jim) and email address (jim@example.com) in C#?

我正在寻找 C# 代码来解析它.

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

我发现 MailAddress 抛出了异常,因为我在电子邮件地址字符串的开头有一个空格.

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

推荐答案

如果您想手动解析电子邮件地址,您需要阅读 RFC2822 (https://tools.ietf.org/html/rfc822.html#section-3.4).3.4 节讨论地址格式.

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

但是正确解析电子邮件地址并不容易,MailAddress 应该能够处理大多数情况.

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

根据 MailAddress 的 MSDN 文档:

According to the MSDN documentation for MailAddress:

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

它应该能够解析带有显示名称的地址.他们以 "Tom Smith " 为例.也许引号是问题?如果是这样,只需去掉引号并使用 MailAddress 解析其余部分.

It should be able to parse an address with a display name. They give "Tom Smith <tsmith@contoso.com>" 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\" <jim@example.com>";

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

如果可以避免,手动解析 RFC2822 不值得麻烦.

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

这篇关于如何将格式化的电子邮件地址解析为显示名称和电子邮件地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆