Sample code for 30+ languages & platforms
SQL Server

Get Each Alternative Body of an Email

See more Email Object Examples

Demonstrates the Chilkat Email.GetAlternativeBody method, which returns the Nth alternative body. The NumAlternatives property gives the number of alternatives, and indexes are zero-based. This example builds a message with plain-text and HTML alternatives and prints each one.

Background: A multipart/alternative email carries the same content in several forms — commonly plain text and HTML. Enumerating them by index lets you pull out exactly the representation you need: showing the HTML in a rich viewer, extracting the plain text for search or indexing, or comparing the two. Pair this with GetAlternativeContentType to learn what each indexed body actually is.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    --  Demonstrates the GetAlternativeBody method, which returns the Nth alternative body.
    --  The NumAlternatives property gives the number of alternatives; indexes are 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

    --  Create an email with plain-text and HTML alternatives.
    EXEC sp_OAMethod @email, 'SetTextBody', NULL, 'This is the plain-text alternative.', 'text/plain'
    DECLARE @success int
    EXEC sp_OAMethod @email, 'AddHtmlAlternativeBody', @success OUT, '<html><body>This is the HTML alternative.</body></html>'

    DECLARE @n int
    EXEC sp_OAGetProperty @email, 'NumAlternatives', @n OUT
    DECLARE @i int

    SELECT @i = 0
    WHILE @i <= @n - 1
      BEGIN


        PRINT '---- Alternative ' + @i + ' ----'
        EXEC sp_OAMethod @email, 'GetAlternativeBody', @sTmp0 OUT, @i
        PRINT @sTmp0
        SELECT @i = @i + 1
      END

    EXEC @hr = sp_OADestroy @email


END
GO