从用户输入文本中提取(多个)电子邮件到MailAddress格式(.NET)

时间:2010-07-05 17:56:19

标签: .net email email-address

MailAddress类没有提供解析包含多个电子邮件的字符串的方法。 MailAddressCollectiondoes,但它只接受CSV,不允许在引号内添加逗号。我正在寻找一个文本处理器来创建一组来自用户输入的电子邮件,没有这些限制。

处理器应采用以下任何格式的逗号或分号分隔值:

"First Middle Last" <fml@example.com>
First Middle Last <fml@example.com>
fml@example.com
"Last, First" <fml@example.com>

4 个答案:

答案 0 :(得分:2)

MailAddressCollection.Add()例程支持以逗号分隔的地址列表。

Dim mc As New Net.Mail.MailAddressCollection()
mc.Add("Bob <bob@bobmail.com>, mary@marymail.com, ""John Doe"" <john.doe@myemail.com>")
For Each m As Net.Mail.MailAddress In mc
    Debug.Print("{0} ({1})", m.DisplayName, m.Address)
Next

输出:

Bob (bob@bobmail.com)
(mary@marymail.com)
John Doe (john.doe@myemail.com)

答案 1 :(得分:1)

开源库DotNetOpenMail(旧)有一个EmailAddress类,可以解析几乎所有合法形式的电子邮件地址,以及EmailAddressCollection。你可以从那里开始。

答案 2 :(得分:1)

在询问related question之后,我意识到了一种更好的方法:

/// <summary>
/// Extracts email addresses in the following formats:
/// "Tom W. Smith" &lt;tsmith@contoso.com&gt;
/// "Smith, Tom" &lt;tsmith@contoso.com&gt;
/// Tom W. Smith &lt;tsmith@contoso.com&gt;
/// tsmith@contoso.com
/// Multiple emails can be separated by a comma or semicolon.
/// Watch out for <see cref="FormatException"/>s when enumerating.
/// </summary>
/// <param name="value">Collection of emails in the accepted formats.</param>
/// <returns>
/// A collection of <see cref="System.Net.Mail.MailAddress"/>es.
/// </returns>
/// <exception cref="ArgumentException">Thrown if the value is null, empty, or just whitespace.</exception>
public static IEnumerable<MailAddress> ExtractEmailAddresses(this string value)
{
    if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("The arg cannot be null, empty, or just whitespace.", "value");

    // Remove commas inside of quotes
    value = value.Replace(';', ',');
    var emails = value.SplitWhilePreservingQuotedValues(',');
    var mailAddresses = emails.Select(email => new MailAddress(email));
    return mailAddresses;
}

/// <summary>
/// Splits the string while preserving quoted values (i.e. instances of the delimiter character inside of quotes will not be split apart).
/// Trims leading and trailing whitespace from the individual string values.
/// Does not include empty values.
/// </summary>
/// <param name="value">The string to be split.</param>
/// <param name="delimiter">The delimiter to use to split the string, e.g. ',' for CSV.</param>
/// <returns>A collection of individual strings parsed from the original value.</returns>
public static IEnumerable<string> SplitWhilePreservingQuotedValues(this string value, char delimiter)
{
    Regex csvPreservingQuotedStrings = new Regex(string.Format("(\"[^\"]*\"|[^{0}])+", delimiter));
    var values =
        csvPreservingQuotedStrings.Matches(value)
        .Cast<Match>()
        .Select(m => m.Value.Trim())
        .Where(v => !string.IsNullOrWhiteSpace(v));
    return values;
}

此方法通过以下测试:

[TestMethod]
public void ExtractEmails_SingleEmail_Matches()
{
    string value = "a@a.a";
    var expected = new List<MailAddress>
        {
            new MailAddress("a@a.a"),
        };

    var actual = value.ExtractEmailAddresses();

    CollectionAssert.AreEqual(expected, actual.ToList());
}

[TestMethod()]
public void ExtractEmails_JustEmailCSV_Matches()
{
    string value = "a@a.a; a@a.a";
    var expected = new List<MailAddress>
        {
            new MailAddress("a@a.a"),
            new MailAddress("a@a.a"),
        };

    var actual = value.ExtractEmailAddresses();

    CollectionAssert.AreEqual(expected, actual.ToList());
}

[TestMethod]
public void ExtractEmails_MultipleWordNameThenEmailSemicolonSV_Matches()
{
    string value = "a a a <a@a.a>; a a a <a@a.a>";
    var expected = new List<MailAddress>
        {
            new MailAddress("a a a <a@a.a>"),
            new MailAddress("a a a <a@a.a>"),
        };

    var actual = value.ExtractEmailAddresses();

    CollectionAssert.AreEqual(expected, actual.ToList());
}

[TestMethod]
public void ExtractEmails_JustEmailsSemicolonSV_Matches()
{
    string value = "a@a.a; a@a.a";
    var expected = new List<MailAddress>
        {
            new MailAddress("a@a.a"),
            new MailAddress("a@a.a"),
        };

    var actual = value.ExtractEmailAddresses();

    CollectionAssert.AreEqual(expected, actual.ToList());
}

[TestMethod]
public void ExtractEmails_NameInQuotesWithCommaThenEmailsCSV_Matches()
{
    string value = "\"a, a\" <a@a.a>; \"a, a\" <a@a.a>";
    var expected = new List<MailAddress>
        {
            new MailAddress("\"a, a\" <a@a.a>"),
            new MailAddress("\"a, a\" <a@a.a>"),
        };

    var actual = value.ExtractEmailAddresses();

    CollectionAssert.AreEqual(expected, actual.ToList());
}

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ExtractEmails_EmptyString_Throws()
{
    string value = string.Empty;

    var actual = value.ExtractEmailAddresses();
}

[TestMethod]
[ExpectedException(typeof(FormatException))]
public void ExtractEmails_NonEmailValue_ThrowsOnEnumeration()
{
    string value = "a";

    var actual = value.ExtractEmailAddresses();

    actual.ToList();
}

答案 3 :(得分:0)

实际上,MailAddressCollection支持以逗号分隔的地址,即使引号内有逗号也是如此。 real problem I recently discovered是CSV列表必须已经编码为ASCII字符集,即。用于Unicode地址的Q编码或B编码。

虽然我在Sasa中提供了B编码,但基类库中没有执行此编码的功能。我还添加了一个电子邮件解析函数来解决这个问题。