8

Im using mailKit in asp mvc core to collect email from a IMAP mailbox.

I return the message using the command

var message = inbox.GetMessage(uid) 

This returns all the results of the message. From here i want to access the sender email address (not including the name). After breakpointing on the above line i can see that the variable message has the following property

message
-From
--From(Array)
---From(item)
----Name (name of the sender)
----Address(email of the sender)

When referencing the above above using the message i am able to receive the name, however the address is not listed (within intelisence, nor will it build)

var name = message.From[0].Name.ToString()

Does anyone know why this would be visible as properties of the variable but not accessible via the code?

i simply want to

var name = message.From[0].Name.ToString()
PowerMan2015
  • 1,307
  • 5
  • 19
  • 40
  • Does `GetMessage` return a dynamic object? Do you get an error when you try this code? Is the property `Name` of type `string`? – adiga Sep 28 '17 at 16:41
  • no error, its just not available when typing in visual studio. But does show ehn i breakpoint and examine the message variable – PowerMan2015 Sep 28 '17 at 16:42

3 Answers3

27

The MimeMessage.From property is a InternetAddressList (more-or-less List<InternetAddress>).

InternetAddress is an abstract base class for MailboxAddress and GroupAddress which only contains a Name property as you've discovered.

In order to get the Address, you first need to cast it to a MailboxAddress... but only if it is actually a MailboxAddress or you'll get a cast exception.

InternetAddressList has a convenience property called Mailboxes which can be used to iterate over a flattened list of the MailboxAddresses contained within.

jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • 2
    var EmailAddress = Message.From.Mailboxes.FirstOrDefault().Address; – niico Dec 25 '20 at 02:53
  • 2
    More information regarding this matter can be found in the [MailKit FAQ](http://www.mimekit.net/docs/html/Frequently-Asked-Questions.htm#AddressHeaders). – vchan Aug 30 '21 at 12:10
1

Another solution:

message.From.Mailboxes.Single().Address;
0

You can use this code block.

message.From.OfType<MailboxAddress>().Single().Address;