Sample code for 30+ languages & platforms
SQL Server

Get an Attachment as Text with CRLF Line Endings

See more Email Object Examples

Demonstrates the Chilkat Email.GetAttachmentStringCrLf method, which retrieves an attachment's data as text with all end-of-line sequences translated to CRLF (\r\n). The first argument is the zero-based attachment index and the second is the charset used to interpret the bytes. This example reads a text attachment and normalizes its line endings to CRLF.

Background: Different systems mark the end of a line differently — Unix uses a single LF (\n), classic Mac used CR, and Windows/most internet protocols use CRLF (\r\n). Text pulled from an attachment can contain any of these. This method normalizes them all to CRLF, which is convenient when the text will be written to a protocol or format that expects consistent CRLF line endings, avoiding mixed-newline surprises.

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
    --  Demonstrates the GetAttachmentStringCrLf method, which retrieves an attachment's data as
    --  text with all end-of-line sequences translated to CRLF.  The first argument is the
    --  zero-based attachment index and the second is the charset used to interpret the bytes.

    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', 'Attachment as text (CRLF)'

    DECLARE @success int
    EXEC sp_OAMethod @email, 'AddStringAttachment', @success OUT, 'notes.txt', 'Line one.' + CHAR(10) + 'Line two.' + CHAR(10) + 'Line three.'

    --  Get the first attachment (index 0) as text with CRLF line endings.
    DECLARE @content nvarchar(4000)
    EXEC sp_OAMethod @email, 'GetAttachmentStringCrLf', @content OUT, 0, 'utf-8'

    PRINT 'Attachment 0 text (CRLF-normalized):'

    PRINT @content

    EXEC @hr = sp_OADestroy @email


END
GO