Sample code for 30+ languages & platforms
Java

Add File Attachments to an Email

Demonstrates how to add one or more file attachments to an email.

Chilkat Java Downloads

Java
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;

    CkEmail email = new CkEmail();

    email.put_Subject("This is a test");
    email.put_Body("This is a test");
    email.put_From("support@chilkatsoft.com");
    success = email.AddTo("Chilkat Admin","admin@chilkatsoft.com");

    // To add file attachments to an email, call AddFileAttachment
    // once for each file to be attached.  The method returns
    // the content-type of the attachment if successful, otherwise
    // returns cknull
    String contentType;

    contentType = email.addFileAttachment("something.pdf");
    if (email.get_LastMethodSuccess() != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    contentType = email.addFileAttachment("something.xml");
    if (email.get_LastMethodSuccess() != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    contentType = email.addFileAttachment("something.zip");
    if (email.get_LastMethodSuccess() != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    success = email.SaveEml("email.eml");
    if (success == false) {
        System.out.println(email.lastErrorText());
        return;
        }

    System.out.println("Saved EML!");
  }
}