How to get a sender's email address?

我只是一个虾纸丫 提交于 2020-03-25 08:23:52

问题


I want Outlook to perform an action on email from a certain email address.

In the ThisOutlookSession I have:

Private Sub Application_NewMail() 'This triggers when a new email is recieved
    Call TestSub
End Sub

In a module I have:

Public Sub TestSub()
    Dim Msg                 As Outlook.MailItem
    Dim FromEmailAddress    As String

    FromEmailAddress = Msg.SenderEmailAddress

    If FromEmailAddress = "Test@example.com" Then
        MsgBox ("Hello")
    End If

End Sub

I get

Run-time error '91':
Object variable or With block variable not set

on FromEmailAddress = Msg.SenderEmailAddress.

I have tried many variations on my code and exhausted the powers of Google.


回答1:


You can use the following code:

Dim oInbox    As Outlook.Folder
Dim oItem     As Object
Dim Msg       As MailItem

Set oInbox = ActiveExplorer.Session.DefaultStore.GetRootFolder().Folders("Inbox")
For Each oItem In oInbox.Items
    If TypeOf oItem Is MailItem Then
        Set Msg = oItem
        FromEmailAddress = Msg.SenderEmailAddress
    Else
        Debug.Print "Skipping " & TypeName(oItem)
    End If
Next



回答2:


Its also good to check if the Sender is SMTP or GetExchangeUser

        Dim Email_Address As String

        If Item.SenderEmailType = "SMTP" Then
            Email_Address = Item.SenderEmailAddress
        Else
            If Item.SenderEmailType = "EX" Then
                Email_Address = Item.Sender.GetExchangeUser.PrimarySmtpAddress
            End If
        End If


来源:https://stackoverflow.com/questions/60444657/how-to-get-a-senders-email-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!