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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; }); | |
} | |
} |