Use Intent to send email with attachment

Description

The following code shows how to Use Intent to send email with attachment.

Example

Main Activity Java code


// w w  w  .  j  ava 2 s. co  m
import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts;
import android.view.Menu;

public class MainActivity extends Activity {

    private Intent mailIntent;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mailIntent = new Intent();
        mailIntent.setAction(Intent.ACTION_SEND);
        mailIntent.setType("message/rfc822");
        mailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"recipient@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_CC, new String[] {"carbon@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_BCC, new String[] {"blind@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
        mailIntent.putExtra(Intent.EXTRA_TEXT, "Body Text");
        mailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fileOne.txt")));
        /*Block for sending multiple attachments
        mailIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        mailIntent.setType("message/rfc822");
        mailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"recipient@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_CC, new String[] {"carbon@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_BCC, new String[] {"blind@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
        mailIntent.putExtra(Intent.EXTRA_TEXT, "Body Text");
        ArrayList<Uri> files = new ArrayList<Uri>();
        files.add(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fileOne.txt")));
        files.add(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fileTwo.txt")));
        //...
        mailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
        */
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("Mail").setIntent(Intent.createChooser(mailIntent, "Mail Client"));
        return true;
    }

}




















Home »
  Android »
    Android Basics »




Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS