Sample code for 30+ languages & platforms
SQL Server

Attach Email as message/rfc822 sub-part to an Email

See more Email Object Examples

Demonstrates how to add attach a message/rfc822 email to another email.

Chilkat SQL Server Downloads

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

    --  In this example, we'll attach an email loaded from a .eml file to a new email.

ERROR: Cannot use pbytes in SQL Server examples...

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

    EXEC sp_OAMethod @fac, 'ReadEntireFile', @emlBytes OUT, 'qa_data/eml/simple.eml'

    DECLARE @email int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @email OUT

    EXEC sp_OASetProperty @email, 'Subject', 'This is a test email with an attached email.'
    EXEC sp_OASetProperty @email, 'Body', 'Test with attached email.'
    EXEC sp_OAMethod @email, 'AddTo', @success OUT, 'Joe', 'joe@example.com'
    EXEC sp_OASetProperty @email, 'From', 'mary@example.com'

    EXEC sp_OAMethod @email, 'AttachMessage', @success OUT, @emlBytes

    EXEC sp_OAMethod @email, 'GetMime', @sTmp0 OUT
    PRINT @sTmp0

    --  ----------------------------------------------------------------------
    --  Alternatively, we could do this:
    DECLARE @emailToBeAttached int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @emailToBeAttached OUT

    EXEC sp_OAMethod @emailToBeAttached, 'LoadEml', @success OUT, 'qa_data/eml/simple.eml'

    DECLARE @email2 int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @email2 OUT

    EXEC sp_OASetProperty @email2, 'Subject', 'This is a test email with an attached email.'
    EXEC sp_OASetProperty @email2, 'Body', 'Test with attached email.'
    EXEC sp_OAMethod @email2, 'AddTo', @success OUT, 'Joe', 'joe@example.com'
    EXEC sp_OASetProperty @email2, 'From', 'mary@example.com'

ERROR: Cannot use pbytes in SQL Server examples...

    EXEC sp_OAMethod @emailToBeAttached, 'GetMimeBinary', @emlBytes2 OUT
    EXEC sp_OAMethod @email2, 'AttachMessage', @success OUT, @emlBytes2


    PRINT '----'

    EXEC sp_OAMethod @email2, 'GetMime', @sTmp0 OUT
    PRINT @sTmp0

    EXEC @hr = sp_OADestroy @fac
    EXEC @hr = sp_OADestroy @email
    EXEC @hr = sp_OADestroy @emailToBeAttached
    EXEC @hr = sp_OADestroy @email2


END
GO