Java Requires Chilkat v11.0.0+
Java
Add an attachment and an inline image
See more Email Object Examples
Add a file attachment from memory and embed an image in the HTML body using its Content-ID. Start with any email that has an HTML body, or use text-and-html.eml from the preceding example. Save the result as with-attachments.eml.
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) {
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Email email = new Email();
try {
email.loadEml("text-and-html.eml");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
BinData data = new BinData();
try {
data.appendString("Time,Activity\r\n09:00,Welcome\r\n10:00,Field session\r\n", "utf-8");
} catch (ChilkatException e) {
System.out.println("Failed: data.AppendString.");
return;
}
try {
email.addAttachmentBd("agenda.csv", data, "text/csv");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// AddRelatedBd returns the identifier that must appear after cid: in the HTML.
BinData image = new BinData();
try {
image.appendEncoded("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAASUlEQVR4nGMQK/ImBv3//x/CYCBSNQkaIKqJ1YCmGkUDsigu1egakOWwqsaiAaICl2p0P8DV4VKNxdP4VWMPJTyqiY04sZGuAQBhyhp6A/ap2AAAAABJRU5ErkJggg==", "base64");
} catch (ChilkatException e) {
System.out.println("Failed: image.AppendEncoded.");
return;
}
String cid;
try {
cid = email.addRelatedBd("confirmed.png", image);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
StringBuilder html = new StringBuilder();
html.append("<p><img alt='Confirmed' src=\"cid:");
html.append(cid);
html.append("\"></p>");
html.append(email.getHtmlBody());
try {
email.addHtmlAlternativeBody(html.getAsString());
email.saveEml("with-attachments.eml");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Saved with-attachments.eml.");
}
}