Alex Roberts
Alex Roberts

Reputation: 66

Extract SMTP address from Exchange User in the FROM field of a message

I want to organize messages in folders by domain (and possibly user). I have a script but it can't get the SMTP addresses from exchange users. The below code is an excerpt from the address extractor.

///For each obj in objFolder.Items
    If obj.SenderEmailAddress = "EX" Then
    Set objSender = obj.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
        If obj.SenderEmailAddress = "" Then
        strSender = "ERROR@ERROR.GOV"
        Else
        MsgBox obj.SenderEmailAddress
        'MsgBox obj.PrimarySmtpAddress 'errs out
        'MsgBox Sender.GetExchangeUser() 'errs out
        'MsgBox Obj.Sender.GetExchangeUser() 'errs out
        strSender = obj.PrimarySmtpAddress
        End If
    End If
///Next

The code works but for those coming from an email group (helpdesk@myexchange.org for example) or spoofed email addresses.

obj.SenderEmailAddress results in "/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP (removedtextforstack)/CN=RECIPIENTS/CN=7E2removedtextforstackF6-USERNAME"

I believe this is to be expected, but Sender.GetExchangeUser() gives an Object Required error. I don't particularly want 3000 lines of code to dig through AD to try to look up an AD code/user for every email. We use office 365 and it's managed by many people, so things aren't straitforward with accessing the address lists.

Upvotes: 1

Views: 1330

Answers (2)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66306

MailItem.Sender.GetExchnageUser().ProimarySmtpAddress should work fine for the EX senders, but your code checks the SenderEmailAddress property instead of SenderEmailType. Change it to

If obj.SenderEmailType = "EX" Then

You can also check the PR_SENT_REPRESENTING_SMTP_ADDRESS property (DASL name http://schemas.microsoft.com/mapi/proptag/0x5D02001F, use MailItem.PropertyAccessor.GetProperty) before using the MailItem.Sender property (which is more expensive)

Upvotes: 1

Alex Roberts
Alex Roberts

Reputation: 66

I have a work-around that seems decently efficient.

Const PR_TRANSPORT_MESSAGE_HEADERS = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"

a = Split(obj.PropertyAccessor.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS), vbCrLf)
For i = 0 To UBound(a)
    If InStr(1, a(i), "From:", vbTextCompare) = 1 Then
    MsgBox Replace(Split(a(i), "<")(1), ">", "")
    End If
Next

This pulls the SMTP address directly from the header and does not care what type of message it is.

There still has to be a better way though...

Upvotes: 0

Related Questions