Sample code for 30+ languages & platforms
Android™

Get an Attachment as a Text String

See more Email Object Examples

Demonstrates the Chilkat Email.GetAttachmentString method, which returns the Nth attachment's data as text. The first argument is the zero-based attachment index and the second is the charset used to interpret the attachment bytes. This example reads a text attachment as utf-8.

Background: Attachments are stored as bytes, so turning one back into a string requires knowing its charset — the rule for mapping bytes to characters. Supplying the correct charset (often utf-8) yields readable text; the wrong one produces garbled characters. This method is meant for text attachments such as .txt, .csv, or .xml; binary attachments should be handled as raw data instead.

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

    //  Demonstrates the GetAttachmentString method, which returns the Nth attachment's data as
    //  text.  The first argument is the zero-based attachment index and the second is the charset used to interpret
    //  the attachment bytes.

    CkEmail email = new CkEmail();
    email.put_Subject("Attachment as text");

    email.AddStringAttachment("notes.txt","These are the notes stored in the attachment.");

    //  Get the first attachment (index 0) as text, interpreting the bytes as utf-8.
    String content = email.getAttachmentString(0,"utf-8");
    Log.i(TAG, "Attachment 0 text: " + content);

  }

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