0

I want to extract the alias part from an email address. For example, if I have "name+alias1+alias2+alias3@email.com", I want it to return a list of subaddresses, in this case alias1, alias2, alias3.

I have code to extract the first alias, like this :

var addr = new MailAddress("name+alias@email.com");
var username = addr.User;
var domain = addr.Host;

if (!username.Contains("+")) return;
var split = username.Split('+').ToList();
var name = split[0];
var alias = split[1];

But this does would not work for multiple addresses. I would also prefer not to use regex (due to "now you have two problems").

WynDiesel
  • 1,104
  • 7
  • 38
  • What if the email address was `name@email.com`? – mjwills Aug 22 '18 at 09:50
  • @mjwills According to RFC 5233, only one plus is allowed, so that should not be considered a valid email address. – WynDiesel Aug 22 '18 at 09:54
  • 1
    Regardless of what the standards docs say, gmail allows there to be two `+` in an email address. So it may be worth considering what you expect to be returned for an input of `name+alias+alias2@email.com`. – mjwills Aug 22 '18 at 09:59
  • Very good point. Just tested this myself, and it worked, I will edit my question. – WynDiesel Aug 22 '18 at 10:01
  • you can either use split or Regex – Liu Aug 22 '18 at 10:08

2 Answers2

1

The trick is using Linq to get all the alias except the first, that corresponds with the name:

    var addr = new MailAddress("name+alias@email.com");
    var username = addr.User;
    var domain = addr.Host;

    if (!username.Contains("+")) return;
    var split = username.Split('+').ToList();
    var name = split[0];
    var alias = split.Skip(1);
mnieto
  • 3,744
  • 4
  • 21
  • 37
1

If you are going to reuse it a lot, I recommend you to write a extension method for retrieving the list of alias. Since @mnieto has already posted a solution with split, here I would like to use Regex.

public static class MailAddressExtension
{
    private static Regex AliasRegex = new Regex(@"\+([A-Za-z0-9]+)");
    public static List<string> Alias(this MailAddress mail)
    {
        return AliasRegex.Matches(mail.User).Select(a => a.Groups[1].Value).ToList();
    }
}

And then in your code, you can just wirte

var addr = new MailAddress("name+alias@email.com");
var username = addr.User;
var domain = addr.Host;
var alias = addr.Alias();
Liu
  • 970
  • 7
  • 19