简体   繁体   中英

Get sender email address

I have the following VBA code which is meant to send an automatic email when a specific subject is received.

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
Dim objNS As Outlook.NameSpace
Set objNS = GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub Items_ItemAdd(ByVal item As Object)
If item.Class = olMail Then
    If Left$(item.Subject, 29) = "Hazard Identification Report" Then
        Dim Msg As Outlook.MailItem
        Dim NewForward As Outlook.MailItem
        Dim myFolder As Outlook.MAPIFolder
        Dim olApp As Outlook.Application
        Dim olNS As Outlook.NameSpace

        Set Msg = item
        Set NewForward = Msg.Forward
        Set olApp = Outlook.Application
        Set olNS = olApp.GetNamespace("MAPI")

        strSender = ""
        strSenderName = Sender.GetExchangeUser().PrimarySmtpAddress

        If itm.SenderEmailAddress = "EX" Then
            Set objSender = itm.Sender
            If Not (objSender Is Nothing) Then
                Set objExchUser = Sender.GetExchangeUser()
                If Not (objExchUser Is Nothing) Then
                    strSender = objExchUser.PrimarySmtpAddress
                End If
            End If
        Else
            strSender = itm.SenderEmailAddress
        End If

I'm getting a compile/object error at the following line:

strSenderName = Sender.GetExchangeUser().PrimarySmtpAddress

the sender name comes up as "empty".

How I can extract the sender's email address?

Originally answered in comments.

Why not msg.SenderEmailAddress

Above accepted answer did not work for me. Instead, I'm using this (works with MeetingItems too):

Function GetSenderEmail(oM As Variant)

   Dim oPA As Outlook.PropertyAccessor
   Set oPA = oM.PropertyAccessor

   GetSenderEmail = oPA.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x5D01001E")

End Function

Thanks to David Lee for the solution in this thread .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM