Sample code for 30+ languages & platforms
SQL Server

Save a MIME Body (Attachment) to a File

See more MIME Examples

Demonstrates the Chilkat Mime.SaveBody method, which writes the decoded body bytes of the current part to a file. The only argument is the file path. Base64 and quoted-printable are decoded; MIME headers and multipart framing are not written.

Note: 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: This is the direct way to extract a part's content to disk — saving an attachment or the payload of a part as its real, decoded bytes. Chilkat reverses the transfer encoding so the file contains the actual content, not its Base64 form. To reach a specific attachment in a multipart message, navigate to that part (for example with PartAt) before calling this.

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 @mime int
    EXEC @hr = sp_OACreate 'Chilkat.Mime', @mime OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @mime, 'LoadMimeFile', @success OUT, 'qa_data/message.eml'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @mime, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mime
        RETURN
      END

    --  Write the decoded body bytes of the current part to a file.  Base64 and quoted-printable are
    --  decoded; MIME headers and multipart framing are not written.  This is how you save an
    --  attachment or the raw content of a part.
    EXEC sp_OAMethod @mime, 'SaveBody', @success OUT, 'qa_output/body_content.dat'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @mime, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mime
        RETURN
      END

    PRINT 'Body saved.'

    EXEC @hr = sp_OADestroy @mime


END
GO