Sample code for 30+ languages & platforms
Java

Get the Content-ID of a Related Item

See more Email Object Examples

Demonstrates the Chilkat Email.GetRelatedContentID method, which returns the Content-ID of a related item (typically an image or style sheet embedded within an HTML email). The index is zero-based. This example loads an image from a file into a BinData object, adds it as a related item with AddRelatedBd (capturing the generated Content-ID and referencing it from the HTML), then reads that Content-ID back.

Background: The Content-ID is the anchor that ties an inline resource to the HTML that displays it: the body references cid: plus the ID, and the matching related part carries that same Content-ID. Because an image is binary, it is loaded into a BinData object (here from a file) and added with AddRelatedBd. Reading the Content-ID back lets a program verify or rewrite those links — for example when relocating embedded images or converting a message for display outside a mail client.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // Demonstrates the GetRelatedContentID method, which returns the Content-ID of a related
        // item.  Related items are typically images and style sheets embedded within HTML emails.
        // The index is zero-based.

        Email email = new Email();
        email.setSubject("GetRelatedContentID example");

        // Load the image data from a file into a BinData object.
        BinData bdImage = new BinData();
        String cid;
        try {
            bdImage.loadFile("qa_data/images/logo.png");

            // Add the image as a related item from the BinData; capture its generated Content-ID.
            cid = email.addRelatedBd("logo.png", bdImage);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Reference the related item in the HTML body by its Content-ID.
        StringBuilder sbHtml = new StringBuilder();
        sbHtml.append("<html><body><img src=\"cid:PLACEHOLDER_CID\"/></body></html>");
        int numReplaced = sbHtml.replace("PLACEHOLDER_CID", cid);
        email.setHtmlBody(sbHtml.getAsString());

        // Read the Content-ID of the first related item (index 0).
        String cid0 = email.getRelatedContentID(0);
        System.out.println("Related item 0 Content-ID: " + cid0);

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