0

I have a code that I was able to string together that logs my sent emails into an excel sheet so i can use that data for other analysis.

In it, I have it resolving the name into an email as outlook shortens it ("Jimenez, Ramon" = email@address.com) as outlook configured this and it works when i send an email to anyone in my company as they are in my address book.

Now, when I email anyone outside it defaults to lastName, firstName so it is not converting this and logging it.

I thought the code I have in here already does this, but I guess not. I have already come this far and I am NOT a software guru at all. Does anyone have insight on how I can also include this as well?? Please see code below:

  Private WithEvents Items As Outlook.Items
  Const strFile As String = "C:\Users\a0227084\Videos\work\test.xlsx"

Private Sub Application_Startup()
  Dim OLApp As Outlook.Application
  Dim objNS As Outlook.NameSpace
  Set OLApp = Outlook.Application
  Set objNS = OLApp.GetNamespace("MAPI")
  ' default local Inbox
  Set Items = objNS.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)

  On Error GoTo ErrorHandler
  Dim Msg As Outlook.MailItem
  If TypeName(item) = "MailItem" Then



    Set Msg = item
    ' ******************

    FullName = Split(Msg.To, ";")

    For i = 0 To UBound(FullName)

    If i = 0 Then
        STRNAME = ResolveDisplayNameToSMTP(FullName(i))
        Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
    ElseIf ResolveDisplayNameToSMTP(FullName(i)) <> "" Then
        STRNAME = ResolveDisplayNameToSMTP(FullName(i))
        Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
    End If

    Next i


    'Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))

  End If
ProgramExit:
  Exit Sub
ErrorHandler:
  MsgBox Err.Number & " - " & Err.Description
  Resume ProgramExit
End Sub

Sub tes2t()



End Sub
Function getRecepientEmailAddress(eml As Variant)
    Set out = CreateObject("System.Collections.Arraylist") ' a JavaScript-y array

    For Each emlAddr In eml.Recipients
        If Left(emlAddr.Address, 1) = "/" Then
            ' it's an Exchange email address... resolve it to an SMTP email address
            out.Add ResolveDisplayNameToSMTP(emlAddr)
        Else
            out.Add emlAddr.Address
        End If
    Next
    getRecepientEmailAddres = Join(out.ToArray(), ";")
End Function
Function ResolveDisplayNameToSMTP(sFromName) As String
    ' takes a Display Name (i.e. "James Smith") and turns it into an email address (james.smith@myco.com)
    ' necessary because the Outlook address is a long, convoluted string when the email is going to someone in the organization.
    ' source:  https://stackoverflow.com/questions/31161726/creating-a-check-names-button-in-excel

    Dim OLApp As Object 'Outlook.Application
    Dim oRecip As Object 'Outlook.Recipient
    Dim oEU As Object 'Outlook.ExchangeUser
    Dim oEDL As Object 'Outlook.ExchangeDistributionList

    Set OLApp = CreateObject("Outlook.Application")
    Set oRecip = OLApp.Session.CreateRecipient(sFromName)
    oRecip.Resolve
    If oRecip.Resolved Then
        Select Case oRecip.AddressEntry.AddressEntryUserType
            Case 0, 5 'olExchangeUserAddressEntry & olExchangeRemoteUserAddressEntry
                Set oEU = oRecip.AddressEntry.GetExchangeUser
                If Not (oEU Is Nothing) Then
                    ResolveDisplayNameToSMTP = oEU.PrimarySmtpAddress
                End If
            Case 10, 30 'olOutlookContactAddressEntry & 'olSmtpAddressEntry
                Dim PR_SMTP_ADDRESS As String
                PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
                ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
        End Select
    End If
End Function
Sub Write_to_excel(str1 As String, str2 As String, str3 As String)
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceWH As Worksheet

Set xlApp = CreateObject("Excel.Application")

With xlApp
.Visible = True
.EnableEvents = False
End With

Set sourceWB = Workbooks.Open(strFile, False, False)
Set sourceWH = sourceWB.Worksheets("Sheet1")



  sourceWB.Activate
  With sourceWH
        lastrow = .Cells(.rows.Count, "A").End(xlUp).Row
  End With



    sourceWH.Cells(lastrow + 1, 1) = str1
    sourceWH.Cells(lastrow + 1, 2) = str2
    sourceWH.Cells(lastrow + 1, 3) = str3

sourceWB.Save
sourceWB.Close

End Sub

Error message and corrected code

Regards, Ramon

1 Answers1

0

First of all, there is no need to create a new Application instance in the ResolveDisplayNameToSMTP method:

Set OLApp = CreateObject("Outlook.Application")

Instead, you can use the Application property available in the Outlook VBA editor out of the box.

Second, you need to use the following code to get the SMTP address from the AddressEntry object:

  Dim PR_SMTP_ADDRESS As String
  Set PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
  ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)

Instead of the following line:

ResolveDisplayNameToSMTP = oRecip.AddressEntry.Address

Read more about that in the How to get the SMTP Address of the Sender of a Mail Item using Outlook Object Model? article.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • So i am getting a compile error? Expected end of statement? Can i not just define the address as a string? I am confused. – xtrubambinoxpr Jan 07 '20 at 16:43
  • I have updated the post, so you could figure out what should be changed. – Eugene Astafiev Jan 07 '20 at 17:08
  • i have updated the original code at the top with an image to show you the error i am receiving. I made these changes already when you informed me about it, but not sure why i am getting this error. Everywhere i see online says i need to use double quotes? but that does not solve my problem. Also, i appreciate all your help so far! – xtrubambinoxpr Jan 07 '20 at 17:14
  • Corrected. You just need to assign a value to the string variable on the next line. – Eugene Astafiev Jan 07 '20 at 17:25
  • Thank you for that. I had to remove the "set" as it was an object that broke the line of code. It is still not converting the email though. it will change the exchange email addresses, but the others (example: Jimenez, Ramon ) are not being converted or logged the website link you provided is no longer available. is that the reason why? @eugeneastafiev – xtrubambinoxpr Jan 07 '20 at 17:35
  • What value is returned from the `GetProperty` method? Did you try to debug? – Eugene Astafiev Jan 07 '20 at 17:38
  • it Comes up as blank.? no value. I cannot step into it as it is triggered when an email is sent, so i am confused how to debug. This is my first code ever. – xtrubambinoxpr Jan 07 '20 at 17:41
  • Ok so i stepped through by putting a break point, but i cannot see the value it returns. it also skips over the Case 10,30 portion that i put in It continues to end function – xtrubambinoxpr Jan 07 '20 at 17:47
  • What value does the `AddressEntryUserType` property return? – Eugene Astafiev Jan 07 '20 at 17:48
  • Ok so if i step through it and it is an outlook exchange email that is shortened (as outlook does it) it will step through to Case 0,5; BUT if it is the other kind that i am trying to log it will skip both case statements... starting to get into the details – xtrubambinoxpr Jan 07 '20 at 17:50
  • how can i see what value is in addressEntryUserType? – xtrubambinoxpr Jan 07 '20 at 17:51
  • I found this, but now nothing is working https://learn.microsoft.com/en-us/office/vba/outlook/Concepts/Address-Book/obtain-the-e-mail-address-of-a-recipient – xtrubambinoxpr Jan 07 '20 at 20:42
  • It is the same approach. It seems your code is not run becaue the `case` operator doesn't hadle all possible values from the `AddressEntryUserType` property. – Eugene Astafiev Jan 08 '20 at 07:56