本answer啓發我想你想要的是這樣的:
Private Sub Application_ItemSend(ByVal Item As Object, ByRef Cancel As Boolean) Handles application.ItemSend
Dim mailItem As Outlook.MailItem = DirectCast(Item, Outlook.MailItem)
Dim sender As Outlook.AddressEntry = mailItem.Sender
Dim senderAddress As String = ""
If sender IsNot Nothing AndAlso
(sender.AddressEntryUserType = Outlook.OlAddressEntryUserType.olExchangeAgentAddressEntry OrElse _
sender.AddressEntryUserType = Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) Then
Dim exchangeUser As Outlook.ExchangeUser = sender.GetExchangeUser()
If exchangeUser IsNot Nothing Then
senderAddress = exchangeUser.PrimarySmtpAddress()
End If
Else
Dim recipient As Outlook.Recipient = application.Session.CreateRecipient(mailItem.SenderEmailAddress)
If recipient IsNot Nothing Then
Dim exchangeUser As Outlook.ExchangeUser = recipient.AddressEntry.GetExchangeUser()
If exchangeUser IsNot Nothing Then
senderAddress = exchangeUser.PrimarySmtpAddress()
End If
End If
'check if senderAddress has been set with above code. If not try SenderEmailAddress
If senderAddress = "" Then
senderAddress = mailItem.SenderEmailAddress()
End If
End If
MessageBox.Show(senderAddress)
End Sub
首先要注意的是,我在鑄造對象Item
到MailItem
。這是我可以正確訪問屬性。我建議你把Option Strict On:
Restricts implicit data type conversions to only widening conversions, disallows late binding, and disallows implicit typing that results in an Object type.
您可能還需要檢查其他OlAddressEntryUserType
秒,但我會留給你。此代碼應至少解決您的錯誤。
但是在回顧了上面的代碼之後,我想知道是否有必要,至少在Application.ItemSend
方法中。我相信這可能會縮小一些像這樣:
Private Sub Application_ItemSend(ByVal Item As Object, ByRef Cancel As Boolean) Handles Application.ItemSend
Dim mailItem As Outlook.MailItem = DirectCast(Item, Outlook.MailItem)
Dim senderAddress As String = mailItem.SenderEmailAddress
Dim recipient As Outlook.Recipient = Application.Session.CreateRecipient(senderAddress)
If recipient IsNot Nothing Then
Dim exchangeUser As Outlook.ExchangeUser = recipient.AddressEntry.GetExchangeUser()
If exchangeUser IsNot Nothing Then
senderAddress = exchangeUser.PrimarySmtpAddress()
End If
End If
MessageBox.Show(senderAddress)
End Sub
什麼是項目的類型?請添加更多相關的代碼。 – Esko
對不起,我編輯過。這有幫助嗎? – danyo
可能重複[什麼是NullReferenceException,以及如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it ) – Bugs