Search code examples
c#parsingmailkitrfc822

is there a good parser for rfc822 formatted email address


usually, these emails come in the form name. I am trying to use MailBoxAddress.Parse to take the name and email address. I am getting too many errors here as it seems that people put their name in any format they want. For example, the following triggers an error:

Alert: xyz's Weather Now - West Association <[email protected]>
Auto Insurance @ full-auto-coverage.com <[email protected]>

Solution

  • I would recommend doing this:

    static MailboxAddress ParseAddr (string input)
    {
        int lt = input.IndexOf ('<');
    
        if (lt == -1)
            throw new FormatException ("Invalid address format");
    
        int gt = input.IndexOf ('>', lt);
    
        if (gt == -1)
            throw new FormatException ("Invalid address format");
    
        var name = input.Substring (0, lt).TrimEnd ();
        var addr = input.Substring (lt + 1, gt - (lt + 1));
    
        return new MailboxAddress (name, addr);
    }