Sample code for 30+ languages & platforms
Android™

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 Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    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) {
        Log.i(TAG, mime.lastErrorText());
        return;
        }

    //  A message body part.
    CkMime bodyPart = new CkMime();
    success = bodyPart.SetBodyFromPlainText("Please see the attached files.");
    if (success == false) {
        Log.i(TAG, bodyPart.lastErrorText());
        return;
        }

    success = mime.AppendPart(bodyPart);
    if (success == false) {
        Log.i(TAG, mime.lastErrorText());
        return;
        }

    //  Attach files directly.
    success = mime.AppendPartFromFile("qa_data/report.pdf");
    if (success == false) {
        Log.i(TAG, mime.lastErrorText());
        return;
        }

    success = mime.AppendPartFromFile("qa_data/photo.jpg");
    if (success == false) {
        Log.i(TAG, mime.lastErrorText());
        return;
        }

    Log.i(TAG, "Number of parts: " + String.valueOf(mime.get_NumParts()));

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}