Java Requires Chilkat v11.0.0+
Java
Find and save an attachment and list inline images
See more Email Object Examples
Find an attachment by filename and media type, then save its decoded bytes to a path you choose. Enumerate inline resources separately to read their Content-IDs.
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("with-attachments.eml");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
StringBuilder filename = new StringBuilder();
StringBuilder mediaType = new StringBuilder();
boolean found = false;
int i = 0;
while (i < email.getNumAttachments()) {
filename.setString(email.getAttachmentFilename(i));
mediaType.setString(email.getAttachmentContentType(i));
if ((filename.contentsEqual("agenda.csv", false)) && ((mediaType.contentsEqual("text/csv", false)) && (!found))) {
BinData data = new BinData();
try {
email.getAttachmentBd(i, data);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
try {
data.writeFile("received-agenda.csv");
} catch (ChilkatException e) {
System.out.println("Failed: data.WriteFile.");
return;
}
System.out.println("Saved attachment: " + data.getNumBytes() + " bytes.");
found = true;
}
i = i + 1;
}
if (!found) {
System.out.println("No matching attachment.");
}
i = 0;
while (i < email.getNumRelatedItems()) {
System.out.println("Related: " + email.getRelatedContentType(i) + " Content-ID: " + email.getRelatedContentID(i));
i = i + 1;
}
}
}