Al Grant
Al Grant

Reputation: 2354

Returning outlook sender address from VBA in Excel

The following code I have copied from this answer here. It triggers the myItems_ItemAdd when a new email is received and is run from within excel. (Note I am not able to call New Mail events directly from outlook)

 Private WithEvents myItems As Outlook.Items

 Private Sub Class_Initialize()
 Dim oNS As Namespace
 Dim myOL As Outlook.Application
 Set myOL = New Outlook.Application
 Set oNS = myOL.GetNamespace("MAPI")
 Set myItems = oNS.GetDefaultFolder(olFolderInbox).Items

 End Sub

Private Sub myItems_ItemAdd(ByVal Item As Object)
  Debug.Print "Got_EMAIL!!!"
End Sub

I then wanted to access various other properties of the email like the subject. This for example works:

Private Sub myItems_ItemAdd(ByVal Item As Object)
  Debug.Print "Got_EMAIL!!!"
  Debug.Print Item.Subject     
End Sub

I would have thought as per the docs that a MailItem (which Item is?) should be accessible with :

Debug.Print Item.Sender

But that results in a Run-time error '287'

enter image description here

I also tried lines:

 Debug.Print Item.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x10130102")
 Debug.Print Item.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0C1F001E")
 Debug.Print Item.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)

Which has the error:

enter image description here

When I inspect the Item object I notice that Sender and MAPIObject are both empty. I have been unable to find an answer to why Sender properties would be accessed through Property Accessor.

How can I access the sender's email address?

*** UPDATE **

Item.Sender.Address results in Run-time error '287' enter image description here

And as previously stated Sender and MAPIObject are both empty:

enter image description here

Upvotes: 1

Views: 383

Answers (1)

xidgel
xidgel

Reputation: 3145

.Sender will return an AddressEntry object (see here) that cannot be handled by Debug.Print. To get the email address as a string use .Sender.Address.

Note: the above gives the expected result when the sender is outside my organization, but not for my colleagues! See here for a possible solution.

Upvotes: 1

Related Questions