Sample code for 30+ languages & platforms
SQL Server

Get the Filename of an Attachment

See more Email Object Examples

Demonstrates the Chilkat Email.GetAttachmentFilename method, which retrieves an attachment's filename as stored in the MIME. The index is zero-based. This example adds an attachment and reads its filename.

Background: An attachment's filename comes from the sender's message and is not guaranteed to be safe or unique — it may include path separators or characters that are awkward on the local filesystem, and two attachments can share a name. When saving attachments to disk, treat this value as untrusted input: sanitize it and guard against collisions (see the OverwriteExisting property, which can auto-generate unique names).

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 GetAttachmentFilename method, which retrieves an attachment's filename
    --  (as stored in the MIME).  The index is zero-based.

    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 filename'

    DECLARE @success int
    EXEC sp_OAMethod @email, 'AddStringAttachment', @success OUT, 'notes.txt', 'Some notes.'

    --  Get the filename of the first attachment (index 0).
    DECLARE @fname nvarchar(4000)
    EXEC sp_OAMethod @email, 'GetAttachmentFilename', @fname OUT, 0

    PRINT 'Attachment 0 filename: ' + @fname

    EXEC @hr = sp_OADestroy @email


END
GO