Click here to Skip to main content
Click here to Skip to main content

Convert HTML to MHTML using ASP.NET

, 14 Jun 2004
Rate this:
Please Sign up or sign in to vote.
An article on how to convert a html document with images to a mhtml document

Introduction

Ever wanted to make a report out of an html document and have it sent to the client for offline use in Word or Excel? An RFC - compliant Multipart MIME Message (mhtml web archive) is one single file containing all related material such as linked documents and images serialized to their Base64 inline encoding representations. There is no native support for creating mhtml archives in .NET but thanks to the Windows CDO library this is easy accomplished.

The code

The projects contains 3 classes; mht, mhtImage and mhtImageCollection. The mht class contains the conversion functions like convertWebControlToMHTString which takes a webControl and a collection of images and returns a string representation of the created mht archive. Use this function when the converting webControl is dependent on user specific Session and Application variables for rendering or when you use dynamically created images.

Public Function convertWebControlToMHTString(ByVal control As WebControl, _
  ByVal MHTimages As mhtImageCollection) As String
  'Render WebControl to html
  Dim html As String = getHtml(control)

  'If WebControl has images, make the html Word compatible
  If Not MHTimages Is Nothing Then
    fixImageLocation(html, MHTimages)
  End If

  Dim msg As New CDO.MessageClass
  Dim stm As ADODB.Stream = Nothing
  Dim MS As System.IO.MemoryStream = Nothing

  Dim iBp As CDO.IBodyPart

  'Make a multipart mhtml document
  Dim mainBody As CDO.IBodyPart
  mainBody = msg
  mainBody.ContentMediaType = "multipart/related"

  'Make the html part of the document
  iBp = mainBody.AddBodyPart()
  iBp.ContentMediaType = "text/html"
  iBp.ContentTransferEncoding = "quoted-printable"
  stm = iBp.GetDecodedContentStream
  stm.WriteText(html)
  stm.Flush()

  'Make the image parts of the document
  If Not MHTimages Is Nothing Then
    Dim oMhtImage As mhtImage
    For Each oMhtImage In MHTimages
      iBp = mainBody.AddBodyPart()
      With iBp
        .ContentMediaType = "image/" + _
 oMhtImage.ImageFormat.ToString().ToLower()
        .ContentTransferEncoding = "base64"

        'ContentLocation must be the same as in the 
        'html part to make them linked
        .Fields.Append("urn:schemas:mailheader:content-location", _
    DataTypeEnum.adBSTR, , , oMhtImage.ContentLocation)
        .Fields.Update()
        .Fields.Refresh()
      End With

      Try
        MS = New System.IO.MemoryStream
        oMhtImage.Image.Save(MS, oMhtImage.ImageFormat)
        Dim bytearray As Byte() = MS.ToArray()
        stm = iBp.GetDecodedContentStream
        stm.Write(bytearray)
        stm.Flush()
      Finally
        MS.Close()
        stm.Close()
      End Try
    Next
  End If

  stm = mainBody.GetStream()
  Return stm.ReadText(stm.Size)
End Function
      

The convertWebPageToMHTString function converts an html document from a specific URL to a mht archive, all images included. Use this function for public html documents not dependent on user specific Session and Application variables.

Public Function convertWebPageToMHTString(ByVal url As String) As String
    Dim msg As New CDO.MessageClass
    Dim stm As ADODB.Stream = Nothing

    Try
        msg.MimeFormatted = True
        msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressNone, "", "")
        stm = msg.GetStream()
        Return stm.ReadText(stm.Size)
    Finally
        stm.Close()
    End Try
End Function
    

The fixImageLocation appends the string "http://" at the beginning of each ContentLocation if not already there, for Word compliance

Private Sub fixImageLocation( _
      ByRef html As String, ByRef MHTimages As mhtImageCollection)
    Dim curContentLocation As String
    Dim curIndex As Integer
    Dim oMhtImage As mhtImage
    For Each oMhtImage In MHTimages
        curContentLocation = oMhtImage.ContentLocation
        If curContentLocation.IndexOf(":") = -1 Then
            curIndex = html.IndexOf(curContentLocation)
            While curIndex <> -1
                html = html.Insert(curIndex, "http://")
                curIndex = html.IndexOf(curContentLocation, curIndex + _
   curContentLocation.Length)
            End While
            oMhtImage.ContentLocation = "http://" + curContentLocation
        End If
    Next
End Sub
    

The mhtImage class contains image information. Property Image contains the actual image. Property ContentLocation contains the path to the image, must be exactly the same as the source for the image in the html part. Property ImageFormat contains the image format (jpg, gif, bmp...)

The mhtImageCollection class contains a collection of mhtImages.

Using the code

Example on how to make a mht archive from a Panel webControl containing one image.

Dim oMhtCol As New mhtImageCollection
oMhtCol.add(New mhtImage(System.Drawing.Image.FromFile( _
  Server.MapPath("/mhtml/images/myComputer.jpg")), _
  "images/myComputer.jpg", System.Drawing.Imaging.ImageFormat.Jpeg))
sendMHTFile(ConvertWebControlToMHTString(Panel1, oMhtCol), "myFirstMht.mht")
    

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Magnus_
Web Developer
Sweden Sweden
Software developer

Comments and Discussions

 
QuestionAny Limit of MHTML file size? PinmemberNirdesh Puri23-Nov-05 21:16 
QuestionHow to Refresh CDOSYS object? PinsussRadhika Datla21-Sep-05 16:50 
AnswerRe: How to Refresh CDOSYS object? PinsussAnonymous21-Sep-05 21:43 
GeneralRe: How to Refresh CDOSYS object? PinsussRadhika Datla21-Sep-05 22:12 
Hi I am reading mail addresses from a CSV file .Fields are email address,recipient's name. I am sending code after setting CDO configuration and sender's address.
First I read the body file contents to "strbody". Now
 
'********************start reading the contents of the address file from the specified location********
 
finaddr = 1
ncurrentLine = 0
nStartLine = CInt(txtstartline.Text) - 1
FileOpen(finaddr, OFD1.FileName, OpenMode.Input)
If (nStartLine <> ncurrentLine) Then
For itemp = ncurrentLine + 1 To nStartLine
If (LOF(finaddr) = 0) Then
MsgBox("Startline is greater than the address line")
Exit Sub
End If
strFullLine = LineInput(Val(finaddr))
If (Len(strFullLine) = 0) Then
MsgBox("address file empty")
End If
Next
ncurrentLine = nStartLine
 
End If
Do Until EOF(finaddr)
strFullLine = LineInput(Val(finaddr))
If (Len(strFullLine) = 0) Then
Exit Do
End If
vSpacePos = Microsoft.VisualBasic.InStr(strFullLine, ",")
strEmailAddr = Microsoft.VisualBasic.Left(strFullLine, vSpacePos - 1)
strName = Microsoft.VisualBasic.Mid(strFullLine, vSpacePos + 1)
vSpacePos = Microsoft.VisualBasic.InStr(strName, ",")
If (vSpacePos <> 0) Then
strName = Microsoft.VisualBasic.Left(strName, vSpacePos - 1)
End If
strEmailTrimed = Trim(strEmailAddr)
 
Do While True
vSpacePos = InStr(strEmailTrimed, " ")
If (vSpacePos = 0) Then
Exit Do
End If
strTemp = Microsoft.VisualBasic.Left(strEmailTrimed, vSpacePos - 1)
strTemp1 = Microsoft.VisualBasic.Mid(strEmailTrimed, vSpacePos + 1)
strTemp1 = Trim(strTemp1)
strEmailTrimed = strTemp & strTemp1
Loop
strEmailAddr = strEmailTrimed
If (Len(strEmailAddr) = 0) Then
Exit Do
End If
 
'*********************Set the email to specified members in the address field**********************
 
oMsg.To = strEmailAddr
oMsg.Subject = txtsubject.Text
Dim myheader As String
myheader = "

Dear "
 
'**********************Open the bodyfile to add custom Header and recipient's name*****************
 
FileOpen(finbody, OFD2.FileName, OpenMode.Output)
Print(finbody, myheader & strName & "" & " ," & "

" & vbCrLf & strBody)
FileClose(finbody)
'MsgBox(strBody)
Dim Bodyfilename As String = OFD2.FileName
'MsgBox(Bodyfilename)
 
'*****************setting HTML mail body **********************************************************
 
oMsg.CreateMHTMLBody("file://\\" & Bodyfilename, CDO.CdoMHTMLFlags.cdoSuppressNone)
'***************************************Sending the email*******************************************
 
oMsg.Send()
 

'************After sending mail, delete the custom header from our file body for not to be repeated
'in next recipient's mail body********************************************************************
 
temfinbody = 3
FileOpen(temfinbody, OFD2.FileName, OpenMode.Output)
Print(temfinbody, strBody)
SaveFileDialog1.RestoreDirectory = True
FileClose(temfinbody)
'MsgBox(strBody)
 
'****Now deleting the attachments because they should not be repeated with the mail of the next recipient's address field****
 
If (Len(addattach.Text) <> 0) Then
For counter = 0 To lstattachment.Items.Count - 1
oMsg.Attachments.DeleteAll()
Next
End If

'******************************increment the loop to read the next addressee*******************************
 
GoTo skipped
skipped:
ncurrentLine = ncurrentLine + 1
icount = icount + 1
Loop
StatusBar1.Text = " MAIL HAS BEEN SENT SUCCESSFULLY! NUMBER OF MESSAGES SENT: " & CStr(icount)
strLastAddrFile = txtsendto.Text
 
'***********close the address file********************************************************************************
FileClose(finaddr)
icount = 0
strBody = ""
Generalslow code Pinmembereerisken1-Aug-05 1:44 
GeneralSaving MHT files in IE Pinmemberbrianp200424-Mar-05 5:42 
GeneralRe: Saving MHT files in IE PinmemberPartenon24-Mar-05 7:03 
GeneralCreateMHTMLBody Pinmemberkikde7-Mar-05 2:05 
GeneralEmbedding CSS Style Sheets Pinmemberbrianp200424-Feb-05 20:59 
GeneralRe: Embedding CSS Style Sheets PinmemberPartenon25-Feb-05 11:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 15 Jun 2004
Article Copyright 2004 by Magnus_
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid