MailKit Converting a InternetAddressList to a MailAddressCollection

If you need to work with email in a .NET environment I highly recommend checking out MailKit by Jeffrey Stedfast. MailKit provides a higher level abstraction working across the different email protocols, which is a massive time saver.

MailKit has its own classes for handling Email Addresses. Most notability the MailboxAddress and InternetAddressList classes are returned when parsing a message envelope.

foreach (var summary in inbox.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure))
{
var tos = summary.Envelope.To;
var replyToList = summary.Envelope.ReplyTo;
}

As powerful as the MailKit constructs are, I typically like to convert any 3rd party types into their .NET framework equivalents.  The below extension method adds a ToMailAddressCollection method to MailKit’s InternetAddressList class.

public static class MailKitExts
{
public static MailAddressCollection ToMailAddressCollection(this InternetAddressList addressList)
{
if(addressList == null)
{
return new MailAddressCollection();
}
return addressList.Mailboxes.Aggregate(new MailAddressCollection(), (c, r) => { c.Add(new MailAddress(r.Address, r.Name)); return c; });
}
}
view raw MailKitExts.cs hosted with ❤ by GitHub