Search code examples
vbaemailms-accessoutlook

Outlook VBA Mailitem property SenderEmailAddress not returning address correctly


So I have a program in access that lets the user select an outlook folder to import to a table. Which then can be selected from a combobox and transferred across to a form for use.

However I am having a problem with one of the values I am getting returned. SenderEmailAddress is not actually giving me an email address, for example this is what I get saved in my table.

I have removed names for privacy.

/O=COMPANY/OU=MAIL12/CN=RECIPIENTS/CN=FIRSTNAME.LASTNAME

Now of course, if I want to pass this value back over to outlook to reply to the email, I cannot use this.

Can anybody help me please?

Public Sub LoadEmails()

    On Error Resume Next

    'Outlook wasn't running, start it from code
    If Started = False Then
        Set olApp = New Outlook.Application '("Outlook.Application")
        Started = True
    End If

    Set myNamespace = olApp.GetNamespace("MAPI")
    Set objFolder = myNamespace.PickFolder

    ' if outlook is closed, it will display this error
    If Err <> 0 Then
        MsgBox "Outlook was closed. Please log out and log back in."
        Started = False
        Exit Sub
    End If

    'Exit if no folder picked.
    If (objFolder Is Nothing) Then
        MsgBox "No Folder Selected"
        Started = False
        Exit Sub
    End If

    Dim adoRS As Recordset
    Dim intCounter As Integer
    Set adoRS = CurrentDb.OpenRecordset("TBL_UserInbox") 'Open table Inbox

    'Cycle through selected folder.
    For intCounter = objFolder.Items.Count To 1 Step -1
        With objFolder.Items(intCounter)
        'Copy property value to corresponding fields
            If .Class = olMail Then
                adoRS.AddNew
                adoRS("Subject") = .Subject
                adoRS("TimeReceived") = .ReceivedTime
                adoRS("Body") = .Body
                adoRS("FromName") = .SenderEmailAddress '<<<  Issue
                adoRS("ToName") = .To
                adoRS.Update
            End If
        End With
    Next

    MsgBox "Completed"

    Started = False
End Sub

Solution

  • That is a perfectly valid email address of type EX (as opposed to SMTP). Check the MailItem.SenderEmailType property. If it is "SMTP", use the SenderEmailAddress property. If it is "EX", use MailItem.Sender.GetExchangeUser.PrimarySmtpAddress. Be prepared to handle nulls/exceptions.