Legend
Legend

Reputation: 116910

Getting an email address instead of a name?

When I am trying to printout the different properties in a MailItem, I am seeing some behavior that I don't understand. Instead of email addresses, I see names.

static void ReadMail()
{
     Microsoft.Office.Interop.Outlook.Application app = null;
     Microsoft.Office.Interop.Outlook._NameSpace ns = null;
     Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;

     app = new Microsoft.Office.Interop.Outlook.Application();
     ns = app.GetNamespace("MAPI");

     inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

      for (int counter = 1; counter <= inboxFolder.Items.Count; counter++)
      {
           dynamic item = inboxFolder.Items[counter];
           Console.WriteLine("Sendername: {0}", item.SenderName);
           Console.WriteLine("Sender: {0}", item.Sender);
           Console.WriteLine("To: {0}", item.To);
       }
 }

What I mean is instead of getting "[email protected]", I am getting "John Doe". Any particular reason this might be happening? Is there a way to obtain the email address of the sender and the recipients (To, CC, BCC) instead of names?

Upvotes: 0

Views: 2684

Answers (3)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66256

Instead of using the To/CC/BCC properties, loop through all recipients in the MailItem.Recipients collection and read the Recipient.Address property. You might also want to use the Recipient.Type (olTo / olCC / OlBCC) property.

foreach (Outlook.Recipient recip in item.Recipients)
{
   if (recip.Type == (int)OlMailRecipientType.olTo)
   {
      Console.WriteLine(string.Format("Name: {0}, address: {1})", recip.Name, recip.Address));
   } 
}

Upvotes: 3

Tommy42
Tommy42

Reputation: 128

Since I can't comment the answer,

You need to cast one of the if member because otherwise it will says that it can not compare an int type with an OlMailRecipientType and the compilation will fail.

here I cast the OlMailRecipientType.OlTo to an int

if (Recip.Type == (int)OlMailRecipientType.olTo)

foreach (Outlook.Recipient recip in item.Recipients)
{
   if (Recip.Type == (int)OlMailRecipientType.olTo)
   {
      Console.WriteLIne(string.Format("Name: {0}, address: {1)", recip.Name, recip.Address));
   } 
}

Upvotes: 0

rufanov
rufanov

Reputation: 3276

Then you should use item.SenderEmailAddress instead of item.SenderName.

Also you can iterate collection item.Recipients to determine Sender/TO/CC/BCC addreses(type is stored in Type property of each Recipient object of that collection) - it has one of Outlook.OlMailRecipientType enumeration values(olOriginator, olTo, olCC, olBCC).

Upvotes: 2

Related Questions