goldb.org home

AS OF MAY 2008, THIS BLOG IS NO LONGER BEING UPDATED.
Visit the new blog at: http://coreygoldberg.blogspot.com



 Wednesday, January 10, 2007

VBScript - Creating a Microsoft Web Archive (*.mht) File Programmatically

Here is a little VBScript for generating a Microsoft Web Archive (*.mht) file.  Web archives are a convenient way to pack a bunch of web files (HTML/CSS/JavaScript) into a single file that is viewable in your browser.  The downside is MHT files are only viewable in MS Internet Explorer (lame).

Normally you would create an MHT by using the "Save As..." option in IE.  This script allows you to create one programmatically.

Sample Usage:

for a remote html file:

>cscript mht_converter.vbs http://www.example.com/temp/foo.html foo.mht


for a local html file:

>cscript mht_converter.vbs file:/temp/foo.html foo.mht



... And now the code:




'mht_converter.vbs

Const adSaveCreateNotExist = 1
Const adSaveCreateOverWrite = 2
Const adTypeBinary = 1
Const adTypeText = 2

Set args = WScript.Arguments

if args.Count = 0 then
WScript.Echo "Usage: [CScript | WScript] mht_converter.vbs <html file> <mht filename>"
WScript.Quit 1
end if

Set objMessage = CreateObject("CDO.Message")
objMessage.CreateMHTMLBody args.Item(0)
SaveToFile objMessage, args.Item(1)


Sub SaveToFile(Msg, Fn)
Dim Strm, Dsk
Set Strm = CreateObject("ADODB.Stream")
Strm.Type = adTypeText
Strm.Charset = "US-ASCII"
Strm.Open
Set Dsk = Msg.DataSource
Dsk.SaveToObject Strm, "_Stream"
Strm.SaveToFile Fn, adSaveCreateOverWrite
End Sub




Caveat:  I am not a VB programmer... don't pretend to be... and never wanna be.  This was just something I needed to do and this was the only way I could quickly figure out how to do it.

#    Comments [2] |
Tuesday, February 13, 2007 3:22:16 PM (Eastern Standard Time, UTC-05:00)
Your solution is simple, elegant, and effective. I've been working on this problem* for two days and thanks to your code, I'm done. I had created the CDO.Message, but did not know how to get MHTML file output from it. Thanks for your post!

*My actual problem is to save an MHTML file from automation of IE without getting stuck with a SaveAs dialog waiting for user input.
Tuesday, February 13, 2007 3:43:16 PM (Eastern Standard Time, UTC-05:00)
Dan,
glad it helped :)
Comments are closed.