如何将格式化的电子邮件地址解析为显示名称和电子邮件地址?

发布于 2024-07-06 09:31:57 字数 523 浏览 9 评论 0原文

给定电子邮件地址:“Jim”[电子邮件受保护]>

如果我尝试将其传递给 MailAddress,我会得到异常:

指定的字符串不符合电子邮件地址所需的格式。

如何将此地址解析为显示名称 (Jim) 和电子邮件地址 ([email protected] ]) 在 C# 中?

编辑:我正在寻找 C# 代码来解析它。

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

白色秋天 2024-07-13 09:31:57

如果您希望手动解析电子邮件地址,则需要阅读 RFC2822 (https://www.rfc-editor.org/rfc/rfc822.html#section-3.4)。 3.4节讨论了地址格式。

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

根据 MailAddress 的 MSDN 文档:

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

它应该能够解析带有显示名称的地址。 他们给“Tom Smith [电子邮件受保护]> “ 为例。 也许引号是问题所在? 如果是这样,只需去掉引号并使用 MailAddress 来解析其余部分。

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

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

如果可以避免的话,手动解析 RFC2822 就不值得了。

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.

生生漫 2024-07-13 09:31:57

对我有用:

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);

MailAddress 类有一个解析电子邮件地址的私有方法。 不知道它有多好,但我倾向于使用它而不是自己编写。

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.

梦里泪两行 2024-07-13 09:31:57

尝试:

"Jimbo <[email protected]>"

Try:

"Jimbo <[email protected]>"
故人如初 2024-07-13 09:31:57

尝试:“Jim” [电子邮件受保护]>
不确定它是否有效,但这就是我在电子邮件客户端中通常看到的方式。

try: "Jim" <[email protected]>
not sure if it'll work, but that's how I generally see it in e-mail clients.

恍梦境° 2024-07-13 09:31:57

如果您假设两者之间始终有空格,则可以使用 String.Split(' ') 将其拆分为空格。 这将为您提供一个各个部分分开的数组。

所以可能是这样的:

string str = "\"Jimbo\" [email protected]"
string[] parts = str.Trim().Replace("\"","").Split(' ')

要检查的一个问题是,如果显示名称中包含空格,它将被分成数组本身中的 2 个或多个项目,但电子邮件将始终是最后一个。

编辑 - 您可能还需要编辑括号,只需添加替换即可。

if you make the assumption there is always a space between the 2, you could just use String.Split(' ') to split it on the spaces. That would give you an array with the parts split.

so maybe like this:

string str = "\"Jimbo\" [email protected]"
string[] parts = str.Trim().Replace("\"","").Split(' ')

An issue with this to check for is that if the display name has a space in it, it will be split into 2 or more items in your array itself, but the email would always be last.

Edit - you might also need to edit out the brackets, just add replaces with those.

℡寂寞咖啡 2024-07-13 09:31:57

我刚刚写了这个,它从字符串中获取第一个格式良好的电子邮件地址。 这样你就不必假设电子邮件地址在字符串中的位置有

很大的改进空间,但我需要去工作:)

class Program
{
    static void Main(string[] args)
    {
        string email = "\"Jimbo\" <[email protected]>";
        Console.WriteLine(parseEmail(email));
    }

    private static string parseEmail(string inputString)
    {
        Regex r = 
            new Regex(@"^((?:(?:(?:[a-zA-Z0-9][\.\-\+_]?)*)[a-zA-Z0-9])+)\@((?:(?:(?:[a-zA-Z0-9][\.\-_]?){0,62})[a-zA-Z0-9])+)\.([a-zA-Z0-9]{2,6})$");

        string[] tokens = inputString.Split(' ');

        foreach (string s in tokens)
        {
            string temp = s;
            temp = temp.TrimStart('<'); temp = temp.TrimEnd('>');

            if (r.Match(temp).Success)
                return temp;
        }

        throw new ArgumentException("Not an e-mail address");
    }
}

I just wrote this up, it grabs the first well formed e-mail address out of a string. That way you don't have to assume where the e-mail address is in the string

Lots of room for improvement, but I need to leave for work :)

class Program
{
    static void Main(string[] args)
    {
        string email = "\"Jimbo\" <[email protected]>";
        Console.WriteLine(parseEmail(email));
    }

    private static string parseEmail(string inputString)
    {
        Regex r = 
            new Regex(@"^((?:(?:(?:[a-zA-Z0-9][\.\-\+_]?)*)[a-zA-Z0-9])+)\@((?:(?:(?:[a-zA-Z0-9][\.\-_]?){0,62})[a-zA-Z0-9])+)\.([a-zA-Z0-9]{2,6})$");

        string[] tokens = inputString.Split(' ');

        foreach (string s in tokens)
        {
            string temp = s;
            temp = temp.TrimStart('<'); temp = temp.TrimEnd('>');

            if (r.Match(temp).Success)
                return temp;
        }

        throw new ArgumentException("Not an e-mail address");
    }
}
深府石板幽径 2024-07-13 09:31:57

它有点“粗糙且准备就绪”,但适用于您给出的示例:

        string emailAddress, displayname;
        string unparsedText = "\"Jimbo\" <[email protected]>";
        string[] emailParts = unparsedText.Split(new char[] { '<' });

        if (emailParts.Length == 2)
        {
            displayname = emailParts[0].Trim(new char[] { ' ', '\"' });
            emailAddress = emailParts[1].TrimEnd('>');
        }

It's a bit "rough and ready" but will work for the example you've given:

        string emailAddress, displayname;
        string unparsedText = "\"Jimbo\" <[email protected]>";
        string[] emailParts = unparsedText.Split(new char[] { '<' });

        if (emailParts.Length == 2)
        {
            displayname = emailParts[0].Trim(new char[] { ' ', '\"' });
            emailAddress = emailParts[1].TrimEnd('>');
        }
瀟灑尐姊 2024-07-13 09:31:57
new MailAddress("[email protected]", "Jimbo");

解析出您给出的字符串:

string input = "\"Jimbo\" [email protected]";
string[] pieces = input.Split(' ');
MailAddress ma = new MailAddress(pieces[1].Replace("<", string.Empty).Replace(">",string.Empty), pieces[0].Replace("\"", string.Empty));
new MailAddress("[email protected]", "Jimbo");

to parse out the string you gave:

string input = "\"Jimbo\" [email protected]";
string[] pieces = input.Split(' ');
MailAddress ma = new MailAddress(pieces[1].Replace("<", string.Empty).Replace(">",string.Empty), pieces[0].Replace("\"", string.Empty));
数理化全能战士 2024-07-13 09:31:57
string inputEmailString = "\"Jimbo\" <[email protected]>";
string[] strSet =  inputEmailString.Split('\"','<','>');   

MailAddress mAddress = new MailAddress(strSet[0], strSet[2]);
string inputEmailString = "\"Jimbo\" <[email protected]>";
string[] strSet =  inputEmailString.Split('\"','<','>');   

MailAddress mAddress = new MailAddress(strSet[0], strSet[2]);
蹲墙角沉默 2024-07-13 09:31:57

要处理嵌入空格,请在括号上拆分,如下所示:

string addrin = "\"Jim Smith\" <[email protected]>";
char[] bracks = {'<','>'};
string[] pieces = addrin.Split(bracks);
pieces[0] = pieces[0]
  .Substring(0, pieces[0].Length - 1)
  .Replace("\"", string.Empty);
MailAddress ma = new MailAddress(pieces[1], pieces[0]);

To handle embedded spaces, split on the brackets, as follows:

string addrin = "\"Jim Smith\" <[email protected]>";
char[] bracks = {'<','>'};
string[] pieces = addrin.Split(bracks);
pieces[0] = pieces[0]
  .Substring(0, pieces[0].Length - 1)
  .Replace("\"", string.Empty);
MailAddress ma = new MailAddress(pieces[1], pieces[0]);
葬﹪忆之殇 2024-07-13 09:31:57

所以,这就是我所做的。 这有点快而且脏,但似乎有效。

string emailTo = "\"Jim\" <[email protected]>";
string emailRegex = @"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])";
string emailAddress = Regex.Match(emailTo.ToLower(), emailRegex).Value;
string displayName = null;

try
{
    displayName = emailTo.Substring(0, emailTo.ToLower().IndexOf(emailAddress) - 1);
}
catch 
{
    // No display name 
}

MailAddress addr = new MailAddress(emailAddress, displayName);

评论?

So, this is what I have done. It's a little quick and dirty, but seems to work.

string emailTo = "\"Jim\" <[email protected]>";
string emailRegex = @"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])";
string emailAddress = Regex.Match(emailTo.ToLower(), emailRegex).Value;
string displayName = null;

try
{
    displayName = emailTo.Substring(0, emailTo.ToLower().IndexOf(emailAddress) - 1);
}
catch 
{
    // No display name 
}

MailAddress addr = new MailAddress(emailAddress, displayName);

Comments?

青衫负雪 2024-07-13 09:31:57

我不使用这种语言编写代码,但我看到您可能需要检查的两个问题:

1-您不知道它被拒绝的确切原因。 最直接的可能性是它有 example.com 的黑名单。

2-您想要的真正解决方案可能是实现严格的验证器。 Stack Overflow 可能是开发这个的好地方,因为有很多有实践经验的人。

这里有一些你需要的东西:

  1. 修剪空白和明显的粗糙。
  2. 解析为各个部分(显示名称、地址左侧、地址右侧)。
  3. 使用数据结构特定的验证器验证其中每一个。 例如,右侧需要是有效的 FQDN(如果您使用的是自由邮件系统,则为不合格的主机名)。

这是解决这个问题的最佳长期方法。

I don't code in this language, but I see two issues you might want to check:

1- You don't know exactly why it was rejected. On immediate possibility was that it has a blacklist for example.com.

2- The real solution you want is to probably implement a strict validator. Stack Overflow is probably a good place to develop this, because there are lots of people with practical experience.

Here are a couple things you need:

  1. trim whitespace and obviously cruft.
  2. parse into individual parts (display name, left-hand-side of address, right-hand side of address).
  3. validate each of these with a data structure specific validator. For example, the right-hand side needs to be a valid FQDN (or unqualified hostname if you are on a liberal mail system).

That's the best long-term approach to solving this problem.

青衫负雪 2024-07-13 09:31:57

我可以建议基于正则表达式的解决方案来解码电子邮件地址字段值(“发件人”、“收件人”)和字段值“主题”

https://www.codeproject.com/Tips/1198601/Parsing-and-Decoding-Values-of-Some-Email-Message

I can suggest my regex-based solution for decoding email address field values ("From", "To") and field value "Subject"

https://www.codeproject.com/Tips/1198601/Parsing-and-Decoding-Values-of-Some-Email-Message

久而酒知 2024-07-13 09:31:57

如果您使用 MailKit,如 推荐,则可以使用MimeKit.MailboxAddress的Parse和TryParse方法。 这是一个例子。

[Test]
public void Should_Parse_EmailAddress_With_Alias()
{
    //Arrange
    var expectedAlias = "Jim";
    var expectedAddress = "[email protected]";
    string addressWithAlias = "\"Jim\" <[email protected]>";

    //Act
    var mailboxAddressWithAlias = MimeKit.MailboxAddress.Parse(addressWithAlias);

    //Assert
    Assert.AreEqual(expectedAddress, mailboxAddressWithAlias.Address);
    Assert.AreEqual(expectedAlias, mailboxAddressWithAlias.Name);
}

If you are using MailKit, as recommended, then you can use the methods Parse and TryParse of MimeKit.MailboxAddress. Here's an example.

[Test]
public void Should_Parse_EmailAddress_With_Alias()
{
    //Arrange
    var expectedAlias = "Jim";
    var expectedAddress = "[email protected]";
    string addressWithAlias = "\"Jim\" <[email protected]>";

    //Act
    var mailboxAddressWithAlias = MimeKit.MailboxAddress.Parse(addressWithAlias);

    //Assert
    Assert.AreEqual(expectedAddress, mailboxAddressWithAlias.Address);
    Assert.AreEqual(expectedAlias, mailboxAddressWithAlias.Name);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文