Create Chooser | Sending Email Using Intent

 

In this blog, we are going to discuss first Intent in short and then create chooser and email sending process using intent.

Intent

An intent is an object that provides runtime binding between seprate components (such as two activity etc). It can be used as signal to the android operating system that certain event has occured.

Intent Object

An intent object is bundle of information which is used by the components.

Intent intent = new Intent();

Intent object contains following property-

1. Action
2. Data
3. Category
4. Extras

Intent Type

Intent are following two types:

1. Explicit Intent

Explicit Intent is the intent in which we explicitly define the component name.

Intent explicitIntent = new Intent(this,SecondActivity.class);

2. Implicit Intent

Implicit Intent is the intent in which we defines action which we want to perform instead of defining component name.

Intent implicitIntent = new Intent();
implicitIntent.setAction(Intent.ACTION_SEND);

createChooser()

If we want to access any Uri like geographical co-ordinate and market store applications then use createChooser(). It returns Intent object. If we did not use create chooser then app will be crash when there is no applications to access the Uri. So whenever we use implicit Intent then we should use create chooser.

Intent intent = new intent(Intent.ACTION_SEND);
Intent chooserIntent = Intent.createChooser(intent,"Send Email")
startActivity(chooserIntent);

Sending Email Using Intent

To send an email from an application you do not have to implement an email client,but you can use default email app provided by android. For this we need to write an activity that launches an email client using implicit intent with right action and data. In the following example we are going  to send an email from our app that launch existing email client

EXTRA_EMAIL – A String[] holding e-mail addresses that should be delivered to.

EXTRA_SUBJECT – A constant string holding the desired subject line of a message.

EXTRA_TEXT – A constant Char Sequence that is associated with the Intent, used email body.

EXTRA_BCC – A String[] holding e-mail addresses that should be blind carbon copied.

EXTRA_CC – A String[] holding e-mail addresses that should be carbon copied.

EXTRA_TITLE – A Char Sequence dialog title to provide to the user when used with a ACTION_CHOOSER.

Intent intent = new Intent(Intent.ACTION_SEND);
//To send an email you need to specify mailto as URI
intent.setData(Uri.parse("mailto:"));
String[] to = {"kps@gmail.com",skaa@gmail.com};
intent.putExtra(Intent.EXTRA_EMAIL,to);
intent.putExtra(Intent.EXTRA_SUBJECT,"Sending Email Using Implicit Intent");
intent.putExtra(Intent.EXTRA_TEXT,"Email body message");

//this is mime type of email without it no activity can be found to send email.
intent.setType("message/rfc822");
chooserIntent = Intent.createChooser(intent,"Send Email");
startActivity(chooserIntent);

 

Leave a Reply