问题
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