Sample code for 30+ languages & platforms
Swift

Add a Related Item from a BinData Object

See more Email Object Examples

Demonstrates the Chilkat Email.AddRelatedBd method, which adds a related item (such as an inline image) using the contents of a BinData object, and returns the generated Content-ID. This example loads an image into a BinData, adds it, captures the Content-ID, and references it from the HTML body.

Background: This is the binary, Content-ID-based way to embed an inline resource — the right choice for images, whose bytes belong in a BinData rather than a string. Because Chilkat generates the Content-ID, the usual pattern is: add the item first, capture the returned ID, then build the matching <img src="cid:..."> reference from it (done here with a StringBuilder).

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Demonstrates the AddRelatedBd method, which adds a related item (such as an inline image)
    //  using the contents of a BinData object, and returns the generated Content-ID.

    let email = CkoEmail()!
    email.subject = "Related image from BinData"

    //  Load the image data from a file into a BinData object.
    let bdImage = CkoBinData()!
    success = bdImage.loadFile(path: "qa_data/images/logo.png")
    if success == false {
        print("\(bdImage.lastErrorText!)")
        return
    }

    //  Add the image as a related item; capture its generated Content-ID.
    var cid: String? = email.addRelatedBd(filename: "logo.png", binData: bdImage)
    if email.lastMethodSuccess == false {
        print("\(email.lastErrorText!)")
        return
    }

    //  Reference the related item in the HTML body by its Content-ID.
    let sbHtml = CkoStringBuilder()!
    sbHtml.append(value: "<html><body><img src=\"cid:PLACEHOLDER_CID\"/></body></html>")
    var numReplaced: Int = sbHtml.replace(value: "PLACEHOLDER_CID", replacement: cid).intValue
    email.setHtmlBody(html: sbHtml.getAsString())

    print("NumRelatedItems = \(email.numRelatedItems.intValue)")

    //  Note: The path "qa_data/images/logo.png" is a relative local filesystem path,
    //  relative to the current working directory of the running application.

}