Outlook 2007 vsto add-in. Get email sender address

前端 未结 4 1170
北荒
北荒 2020-12-31 11:38

I have a VSTO Outlook 2007 add-in. I am trying to get sender e-mail address when new email comes to Inbox.
To do it I use the following code:

void inbox         


        
4条回答
  •  伪装坚强ぢ
    2020-12-31 11:59

    Here I am presenting a method that can be used to get sender's email address by passing an email item as a reference. The method it self will decide weather the sender's email address type is SMTP or Exchange. If it is Exchange, it will convert the email address into SMTP. Here is the code.

        internal static string GetSenderEmailAddress(ref Outlook.MailItem oM)
        {
            Outlook.PropertyAccessor oPA = null;
            Outlook.AddressEntry oSender = null;
            Outlook.ExchangeUser oExUser = null;
    
            string SenderID;
            string senderEmailAddress;
    
            try
            {                
                if (oM.SenderEmailAddress.Contains("@") && oM.SenderEmailAddress.Contains(".com")) //Handing smtp email addresses
                {
                    senderEmailAddress = oM.SenderEmailAddress;
                }
                else //Handing exchange email addresses
                {
                    // Create an instance of PropertyAccessor 
                    oPA = oM.PropertyAccessor;
                    // Obtain PidTagSenderEntryId and convert to string 
                    SenderID = oPA.BinaryToString(oPA.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0C190102"));
                    // Obtain AddressEntry Object of the sender 
                    oSender = Globals.ObjNS.GetAddressEntryFromID(SenderID);
    
                    oExUser = oSender.GetExchangeUser();
                    senderEmailAddress = oExUser.PrimarySmtpAddress;
                }
                Debug.DebugMessage(3, "OutlookHelper : GetSenderEmailAddress() : Completed");
                return senderEmailAddress;
            }
            catch (Exception ex)
            {
                MessageBox.Show( ex.Message);
                return null;
            }
            finally
            {
                if (oExUser != null) Marshal.ReleaseComObject(oExUser);
                if (oSender != null) Marshal.ReleaseComObject(oSender);
                if (oPA != null) Marshal.ReleaseComObject(oPA);
            }
        }
    

提交回复
热议问题