Java
Java
Attach a File to a Multipart MIME Entity
See more MIME Examples
Demonstrates the Chilkat Mime.AppendPartFromFile method, which reads a local file, creates an attachment part, and appends it. The only argument is the file path; the content headers are chosen from the filename extension.
Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.
Background: This is the one-call way to add an attachment: Chilkat reads the file, infers its
Content-Type from the extension, base64-encodes binary content, and appends it as a child part — typically inside a multipart/mixed. It is the building block behind adding attachments to an email, saving you from constructing the part and setting its headers by hand.Chilkat Java Downloads
import com.chilkatsoft.*;
public class ChilkatExample {
static {
try {
System.loadLibrary("chilkat");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
public static void main(String argv[])
{
boolean success = false;
// Demonstrates the Mime.AppendPartFromFile method, which reads a local file, creates an attachment
// part, and appends it. The only argument is the file path; the content headers are chosen from
// the filename extension.
CkMime mime = new CkMime();
success = mime.NewMultipartMixed();
if (success == false) {
System.out.println(mime.lastErrorText());
return;
}
// A message body part.
CkMime bodyPart = new CkMime();
success = bodyPart.SetBodyFromPlainText("Please see the attached files.");
if (success == false) {
System.out.println(bodyPart.lastErrorText());
return;
}
success = mime.AppendPart(bodyPart);
if (success == false) {
System.out.println(mime.lastErrorText());
return;
}
// Attach files directly.
success = mime.AppendPartFromFile("qa_data/report.pdf");
if (success == false) {
System.out.println(mime.lastErrorText());
return;
}
success = mime.AppendPartFromFile("qa_data/photo.jpg");
if (success == false) {
System.out.println(mime.lastErrorText());
return;
}
System.out.println("Number of parts: " + mime.get_NumParts());
}
}