Sample code for 30+ languages & platforms
Android™

Save All Email Attachments to a Directory

See more Email Object Examples

Demonstrates the Chilkat Email.SaveAllAttachments method, which saves all of the email's attachments to a directory. If the directory or any of its components do not exist, Chilkat creates them automatically. This example adds two attachments and saves them.

Background: Each attachment is written using its own filename. Because those filenames come from the sender and may collide, consider the OverwriteExisting property (which can auto-generate unique names) and RemoveAttachmentPaths (which strips embedded path info) to keep saved files safe and non-clobbering — important when processing untrusted incoming mail.

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 SaveAllAttachments method, which saves all attachments to a directory.
    //  If the directory (or any of its components) does not exist, Chilkat creates it.

    CkEmail email = new CkEmail();
    email.put_Subject("Save all attachments");

    email.AddStringAttachment("a.txt","first attachment");
    email.AddStringAttachment("b.txt","second attachment");

    //  Save every attachment into the specified directory.
    success = email.SaveAllAttachments("qa_output/attachments");
    if (success == false) {
        Log.i(TAG, email.lastErrorText());
        return true;
        }

    Log.i(TAG, "Saved all attachments.");

    //  Note: The path "qa_output/..." is a relative local filesystem path,
    //  relative to the current working directory of the running application.

  }

  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."
  }
}