Outlook VBA— Some MailItem Properties return values, others do not

北城以北 提交于 2019-12-02 05:24:29

Multiple Item Types

First, there is no guarantee that all items in the Inbox.Items collection are of type MailItem. Inboxes also contain AppointmentItem, MeetingItem, and other *Item type objects. Not all of these item types have the same properties populated. To ensure you do not get a type mismatch error, declare your iterator variable as a generic Object and only assign it to a strongly-typed MailItem variable if it is of the correct type:

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

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

Optional properties

Second, there is no gaurantee that all properties of an object will be populated. If a mail item was never sent, it will have no sender address, and certainly it is possible to have an email with no body. A good way to get familiar with which properties are available and what they contain is to use the Locals window (View > Locals Window in the VBA IDE). Here's a screen shot of the above code paused in the loop, with some of the properties of the oMailItem object expanded:

Body vs. HTMLBody

MailItem objects have three body properties: Body, HTMLBody, and RTFBody. Usually only one of them is populated. Which one depends on the format of the email. You can check the BodyFormat property to find which one is applicable to the current item. Using that, here's a generalized way to get the raw body of a MailItem, no matter what the format:

Public Function MailBody(ByVal MailItem As MailItem) As String
    Select Case MailItem.BodyFormat
        Case OlBodyFormat.olFormatPlain, OlBodyFormat.olFormatUnspecified
            MailBody = MailItem.Body
        Case OlBodyFormat.olFormatHTML
            MailBody = MailItem.HTMLBody
        Case OlBodyFormat.olFormatRichText
            MailBody = MailItem.RTFBody
    End Select
End Function
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!