Java
Chilkat2 Java
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 Java Downloads
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 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.
Email email = new Email();
email.setSubject("Related image from BinData");
// 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; 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());
System.out.println("NumRelatedItems = " + email.getNumRelatedItems());
// Note: The path "qa_data/images/logo.png" is a relative local filesystem path,
// relative to the current working directory of the running application.
}
}