Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Sending an Email using Intents

Author: Rachee Singh
Published? false
FormatLanguage: WikiFormat

Problem:

You need to send an Email through your application

Solution:

Using action ACTION_SEND with an intent and starting the mailing app existing on the phone.

Discussion:

Just as opening the phone dialer from your app allows the user to make calls, opening the mailing application on the device allows the user to send emails. This can be done very simply:

final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

This intent can used to start the standard mailing app of the phone using the createChooser method like this:

MailMe.this.startActivity(Intent.createChooser(emailIntent, "Send Mail using:"));

Where MailMe is the class name of the Activity. This shows an alert, asking which app to use for sending an email. On a real device it would open the mailing apps present on the phone. Since there is no mailing app on an Emulator, the alerts shows a message 'No applications can perform this action.'.

Even though the mail is sent through the mailing app on the phone, from your app you can provide the details like sender's email ID, subject of the mail and content of the mail so that the user can select or type these details within your app, and from the mailing app (s)he can just hit 'Send'. For this, we can ask the user to input the his/her email address, email's subject and text of the email and then send these inputs along with the intent that we used to fire up the phone's mailing app. Sending information along with an intent is a standard process and it is done using the putExtra method:

final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ senderAddress.getText().toString()});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext.getText());
MailMe.this.startActivity(Intent.createChooser(emailIntent, "Send a Mail through.."));

Here is how a layout for the app can be made.

From these Edit texts, we have extracted the content and used it in putExtra method.

No records found.