Sample code for 30+ languages & platforms
SQL Server

Unpack MHT MIME Text into Files

See more MHT / HTML Email Examples

Demonstrates Mht.UnpackMHTString, which extracts MHT data into its constituent parts: the HTML document and its referenced resources. The source is MHT MIME text supplied as a string.

The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background. Despite the method name, the source may be either literal MHT MIME text or a local MHT file path; Chilkat distinguishes the two by detecting MIME headers. The HTML is written under the chosen filename, and referenced parts are written into a sub-directory.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    DECLARE @mht int
    EXEC @hr = sp_OACreate 'Chilkat.Mht', @mht OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    --  The file paths are relative to the application's current working directory.  Absolute paths may
    --  also be used.  Supply the paths appropriate to your own environment.

    --  Load the MHT MIME text into a string.
    DECLARE @sbMht int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbMht OUT

    DECLARE @bLoaded int
    EXEC sp_OAMethod @sbMht, 'LoadFile', @bLoaded OUT, 'qa_data/page.mht', 'utf-8'
    IF @bLoaded <> 1
      BEGIN

        PRINT 'Failed to load the MHT file.'
        EXEC @hr = sp_OADestroy @mht
        EXEC @hr = sp_OADestroy @sbMht
        RETURN
      END

    --  Unpack the MHT MIME text into its constituent parts.  The 1st argument may be MHT MIME text or a
    --  file path; the 2nd is the unpack directory, the 3rd is the main HTML filename, and the 4th is the
    --  sub-directory (relative to the unpack directory) for the referenced parts such as images and style
    --  sheets.
    EXEC sp_OAMethod @sbMht, 'GetAsString', @sTmp0 OUT
    EXEC sp_OAMethod @mht, 'UnpackMHTString', @success OUT, @sTmp0, 'qa_output/unpacked', 'index.html', 'parts'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @mht, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mht
        EXEC @hr = sp_OADestroy @sbMht
        RETURN
      END

    PRINT 'MHT unpacked.'

    EXEC @hr = sp_OADestroy @mht
    EXEC @hr = sp_OADestroy @sbMht


END
GO