Sample code for 30+ languages & platforms
SQL Server

Attach a File to an Email

See more Email Object Examples

Demonstrates the Chilkat Email.AddFileAttachment method, which attaches a file read from the filesystem. It returns the content type Chilkat assigned to the attachment (inferred from the file extension). This example attaches a PDF and prints its detected content type.

Background: Each attachment carries a Content-Type (MIME type) such as application/pdf or image/png that tells the receiving client how to handle it. Chilkat gets this from the file's extension. Because attachment bytes are binary, they are Base64-encoded for transport, which is handled automatically — you simply point AddFileAttachment at a path and the file is read, encoded, and packaged into the message.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    DECLARE @sTmp0 nvarchar(4000)
    --  Demonstrates the AddFileAttachment method, which attaches a file read from the
    --  filesystem.  It returns the content type Chilkat assigned to the attachment (based on
    --  the file extension), or returns failure if the file could not be read.

    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', 'Email with a file attachment'
    EXEC sp_OASetProperty @email, 'Body', 'Please see the attached file.'

    --  Attach a file.  The return value is the auto-detected content type.
    DECLARE @contentType nvarchar(4000)
    EXEC sp_OAMethod @email, 'AddFileAttachment', @contentType OUT, 'qa_data/attachments/report.pdf'
    EXEC sp_OAGetProperty @email, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 = 0
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        RETURN
      END


    PRINT 'Attached content type = ' + @contentType

    EXEC sp_OAGetProperty @email, 'NumAttachments', @iTmp0 OUT
    PRINT 'NumAttachments = ' + @iTmp0

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

    EXEC @hr = sp_OADestroy @email


END
GO