Sample code for 30+ languages & platforms
PureBasic

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 PureBasic Downloads

PureBasic
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkEmail.pb"

Procedure ChilkatExample()

    ;  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.

    email.i = CkEmail::ckCreate()
    If email.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkEmail::setCkSubject(email, "Email with a related style sheet")

    ;  Add the text-based related resource first; capture the generated Content-ID.
    cid.s = CkEmail::ckAddRelatedString(email,"styles.css","body { color: navy; }","utf-8")
    If CkEmail::ckLastMethodSuccess(email) = 0
        Debug CkEmail::ckLastErrorText(email)
        CkEmail::ckDispose(email)
        ProcedureReturn
    EndIf

    ;  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.
    sbHtml.i = CkStringBuilder::ckCreate()
    If sbHtml.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(sbHtml,"<html><head><link rel=" + Chr(34) + "stylesheet" + Chr(34) + " href=" + Chr(34) + "cid:PLACEHOLDER_CID" + Chr(34) + "/></head><body>Styled content.</body></html>")
    numReplaced.i = CkStringBuilder::ckReplace(sbHtml,"PLACEHOLDER_CID",cid)
    CkEmail::ckSetHtmlBody(email,CkStringBuilder::ckGetAsString(sbHtml))

    Debug "Related Content-ID = " + cid
    Debug "NumRelatedItems = " + Str(CkEmail::ckNumRelatedItems(email))


    CkEmail::ckDispose(email)
    CkStringBuilder::ckDispose(sbHtml)


    ProcedureReturn
EndProcedure