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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/162681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:18:14  来源:igfitidea点击:

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

c#parsingmailaddress

提问by Dylan

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

鉴于电子邮件地址:“Jim”<[email protected]>

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

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

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#?

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

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

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

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

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

采纳答案by Brannon

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.

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

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

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

According to the MSDN documentation for MailAddress:

根据 MSDN 文档MailAddress

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

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.

它应该能够解析带有显示名称的地址。他们举"Tom Smith <[email protected]>"个例子。也许引号是问题?如果是这样,只需去掉引号并使用 MailAddress 解析其余部分。

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

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

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

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

回答by Codewerks

Try:

尝试:

"Jimbo <[email protected]>"

回答by Wayne

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

回答by Sekhat

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

尝试:“Jim”<[email protected]> 不确定它是否会起作用,但我通常在电子邮件客户端中看到它。

回答by Vivek

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

MailAddress mAddress = new MailAddress(strSet[0], strSet[2]);

回答by Carlton Jenke

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.

如果您假设 2 之间始终存在空格,则可以使用 String.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.

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

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

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

回答by FlySwat

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

回答by Rob

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('>');
        }

回答by b w

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

回答by Dylan

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?

注释?