Sample code for 30+ languages & platforms
SQL Server

Save an Email to a .eml File

See more Email Object Examples

Demonstrates the Chilkat Email.SaveEml method, which converts the email object to EML and saves it to a file. An EML file contains the complete RFC822/MIME message — headers, bodies, related items, and attachments. This example builds a message and saves it.

Background: Saving as .eml writes the message in the universal MIME format that virtually every mail client can open, making it ideal for archiving, sharing, or handing a message to another program. It is the counterpart to LoadEml. A saved .eml also retains Chilkat's CKX- metadata headers (a way to store your own metadata with the email; they are always stripped before an email is sent), so .eml is the recommended way to persist a message even within Chilkat-based software. A separate Chilkat XML format (SaveXml) exists as an alternative, but offers no metadata advantage over .eml.

Chilkat SQL Server Downloads

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

    --  Demonstrates the SaveEml method, which converts the email object to EML and saves it to
    --  a file.  An EML file contains the complete RFC822/MIME message, including headers,
    --  bodies, related items, and attachments.

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

    EXEC sp_OASetProperty @email, 'Subject', 'Save as EML'
    EXEC sp_OASetProperty @email, 'From', 'alice@example.com'
    EXEC sp_OAMethod @email, 'AddTo', @success OUT, 'Bob', 'bob@example.com'
    EXEC sp_OASetProperty @email, 'Body', 'Hello, this message will be saved as a .eml file.'

    --  Save the email to a .eml file.
    EXEC sp_OAMethod @email, 'SaveEml', @success OUT, 'qa_output/message.eml'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        RETURN
      END


    PRINT 'Saved to message.eml.'

    --  Note: The path "qa_output/..." is a relative local filesystem path,
    --  relative to the current working directory of the running application.

    EXEC @hr = sp_OADestroy @email


END
GO