Sample code for 30+ languages & platforms
SQL Server

Enumerate the Header Fields of an Email

See more Email Object Examples

Demonstrates the read-only Chilkat Email.NumHeaderFields property together with GetHeaderFieldName and GetHeaderFieldValue to enumerate every header field. Indexing is zero-based, so fields run from 0 to NumHeaderFields - 1. Repeated header fields (a field name that appears more than once) are counted separately. This example builds a small email and prints each header field.

Background: A header field is a single Name: value line at the top of a MIME message. The same field name can legitimately appear multiple times — for example, a message can carry several Received lines, one added by each mail server it passed through. That is why enumerating by index (rather than looking up by name) matters: it lets you see every occurrence in the order it appears.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @sTmp1 nvarchar(4000)
    --  Demonstrates the read-only Email.NumHeaderFields property and enumerating each
    --  header field by zero-based index using GetHeaderFieldName and GetHeaderFieldValue.

    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', 'Header field enumeration'
    EXEC sp_OASetProperty @email, 'From', 'mary@example.com'
    DECLARE @success int
    EXEC sp_OAMethod @email, 'AddTo', @success OUT, 'Joe', 'joe@example.com'

    DECLARE @n int
    EXEC sp_OAGetProperty @email, 'NumHeaderFields', @n OUT

    PRINT 'NumHeaderFields = ' + @n

    DECLARE @i int

    SELECT @i = 0
    WHILE @i <= @n - 1
      BEGIN
        EXEC sp_OAMethod @email, 'GetHeaderFieldName', @sTmp0 OUT, @i

        EXEC sp_OAMethod @email, 'GetHeaderFieldValue', @sTmp1 OUT, @i
        PRINT @sTmp0 + ': ' + @sTmp1
        SELECT @i = @i + 1
      END

    EXEC @hr = sp_OADestroy @email


END
GO