Sample code for 30+ languages & platforms
DataFlex

Add a Related String Resource to an Email

See more Email Object Examples

Demonstrates the Chilkat Email.AddRelatedString method, which adds a text-based related MIME resource, such as a style sheet, from an in-memory string and returns the generated Content-ID. The first argument is the MIME resource name, the second is the text content, and the third is the charset used to encode it. Because the Content-ID is generated by the call, this example adds the style sheet first, then builds an HTML body in a StringBuilder that references the style sheet by that cid:, and passes the result to SetHtmlBody.

Background: Related items are not always images loaded from disk — sometimes the resource is text you already have in memory, like a generated CSS style sheet or an SVG. AddRelatedString lets you embed such content directly without writing a temporary file first. As with other related items, it lives in the multipart/related enclosure and is referenced from the HTML by the Content-ID the method returns.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Handle hoEmail
    String sCid
    Handle hoSbHtml
    Boolean iSuccess
    Integer iNumReplaced
    String sTemp1
    Integer iTemp1
    Boolean bTemp1

    //  Demonstrates the AddRelatedString method, which adds a text-based related MIME resource
    //  (such as a style sheet) from an in-memory string and returns the generated Content-ID.
    //  The first argument is the resource name, the second is the text content, the third is the charset.

    Get Create (RefClass(cComChilkatEmail)) To hoEmail
    If (Not(IsComObjectCreated(hoEmail))) Begin
        Send CreateComObject of hoEmail
    End
    Set ComSubject Of hoEmail To "Email with a related style sheet"

    //  Add the text-based related resource first; capture the generated Content-ID.
    Get ComAddRelatedString Of hoEmail "styles.css" "body { color: navy; }" "utf-8" To sCid
    Get ComLastMethodSuccess Of hoEmail To bTemp1
    If (bTemp1 = False) Begin
        Get ComLastErrorText Of hoEmail To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Build the HTML body, referencing the related style sheet by its Content-ID.  A
    //  placeholder is used and then replaced with the actual Content-ID.
    Get Create (RefClass(cComChilkatStringBuilder)) To hoSbHtml
    If (Not(IsComObjectCreated(hoSbHtml))) Begin
        Send CreateComObject of hoSbHtml
    End
    Get ComAppend Of hoSbHtml '<html><head><link rel="stylesheet" href="cid:PLACEHOLDER_CID"/></head><body>Styled content.</body></html>' To iSuccess
    Get ComReplace Of hoSbHtml "PLACEHOLDER_CID" sCid To iNumReplaced
    Get ComGetAsString Of hoSbHtml To sTemp1
    Send ComSetHtmlBody To hoEmail sTemp1

    Showln "Related Content-ID = " sCid
    Get ComNumRelatedItems Of hoEmail To iTemp1
    Showln "NumRelatedItems = " iTemp1


End_Procedure