Estratto (multipli) email da testo di input degli utenti nel formato MailAddress (NET)

StackOverflow https://stackoverflow.com/questions/3181335

  •  02-10-2019
  •  | 
  •  

Domanda

Il MailAddress classe doesn' t fornire un modo per analizzare una stringa con più messaggi di posta elettronica. Il MailAddressCollection classe fa , ma accetta solo CSV e non consente le virgole all'interno di citazioni . Sto cercando un elaboratore di testo per creare una raccolta di email da input dell'utente senza queste restrizioni.

Il processore dovrebbe assumere valori da virgole o virgola separato in uno dei seguenti formati:

"First Middle Last" <fml@example.com>
First Middle Last <fml@example.com>
fml@example.com
"Last, First" <fml@example.com>
È stato utile?

Soluzione 3

Dopo aver chiesto una questione connessa , sono venuto a conoscenza di un metodo migliore:

/// <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;
}

Questo metodo passa le seguenti prove:

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

Altri suggerimenti

Il MailAddressCollection.Add () supporti di routine un elenco di indirizzi delimitato da virgole.

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

Output:

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

La libreria open source DotNetOpenMail (vecchio) ha una classe EmailAddress in grado di analizzare quasi tutte le forme giuridiche di indirizzi di posta elettronica, e un EmailAddressCollection . Si potrebbe cominciare da lì.

In realtà, MailAddressCollection supportati da indirizzi delimitati da virgole, anche con le virgole all'interno delle virgolette. Il vero problema da poco ho scoperto , è che l'elenco CSV deve già essere codificati nel set di caratteri ASCII, cioè. Q-codificati o B-codificati per gli indirizzi Unicode.

Non c'è alcuna funzione nelle librerie di classi di base per eseguire questa codifica, anche se fornisco B-codificante in Sasa . Ho anche appena aggiunto una funzione di parsing e-mail, che affronta la questione in questo thread.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top