0

I am trying to get sender's email address for an Outlook mailbox through C# code. I tried this link but I am getting "Object reference not set to an instance of an object" for senderEmail = objAddressentry.GetExchangeUser().PrimarySmtpAddress line. My code is as follows:

Outlook.Application oApp = new Outlook.Application();
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
Outlook.MailItem olMail = new Outlook.MailItem();

if (olMail.SenderEmailType == "EX")
{

   var objReply = olMail.Reply();
   var objRecipient = objReply.Recipients[1]; 

   var strEntryId = objRecipient.EntryID;

   var objAddressentry = oNS.GetAddressEntryFromID(strEntryId);
   string senderEmail = objAddressentry.GetExchangeUser().PrimarySmtpAddress;
}

I will appreciate any help.

If it is of any help, I came across this link, but my AddressEntryUserType comes as olExchangeDistributionListAddressEntry, which is why the control doesn't go inside the If branch.

Kanu Priya
  • 77
  • 1
  • 8

1 Answers1

0

As pointed earlier by, my code is correct. It throws the "Object reference not set to an instance of an object" exception for objAddressentry.GetExchangeUser(), when AddressEntryUserType for Sender is of olExchangeDistributionListAddressEntry type. Modified code is as follows:

if (olMail.SenderEmailType == "EX")
   {

         var objReply = olMail.Reply();
         Outlook.Recipient objRecipient = objReply.Recipients[1]; 
         string strEntryId = objRecipient.EntryID;
         Outlook.AddressEntry objAddressentry = oNS.GetAddressEntryFromID(strEntryId);

         if (objAddressentry != null)
         {

             Outlook.ExchangeUser eu = objAddressentry.GetExchangeUser();
             if (eu != null)
                senderEmail = eu.PrimarySmtpAddress; 

          }

 }
Kanu Priya
  • 77
  • 1
  • 8