Search code examples
vbscriptoutlookqtp

Not able to extract full HTMLBODY in vbscript


I want to view the source of an outlook mail and save it as an HTML file. But the mailItem.HTMLBody is not giving me full source, it is truncated in the mid.

Set app = CreateObject("Outlook.Application")
Set nameSpace = app.GetNamespace("MAPI")
Set MyFolders = nameSpace.GetDefaultFolder(6)
'Read unread items in Inbox
Set cols = MyFolders.Items
dim a
For each mail In cols
If mail.unread Then
a = mail.HTMLbody
msgbox a
End If
Next
'MSgbox a doesn't show full html source*

Solution

  • The .HTMLbody property is complete. It's MsgBox() that truncates the string.

    Save it to file, just as you originally intended.

    Set FSO = CreateObject("Scripting.FileSystemObject")
    
    ' ...
    
    For Each mail In cols
      If mail.unread Then
        With FSO.CreateTextFile("C:\Temp\messagebody.html", True, True)
          .Write mail.HTMLbody
          .Close
        End With
      End If
    Next
    

    If you plan on using the message subject as the filename, make sure that you replace all characters that are invalid in filenames and that you the check overall path length limit (~255 characters).

    The FileSystemObject is documented here: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/createtextfile-method