Android Sending Email Example

o send an email from your application, you don’t have to implement an email client from the beginning, but you can use an existing one like the default Email app provided from Android, Gmail, Outlook, K-9 Mail etc. For this purpose, we need to write an Activity that launches an email client, using an implicit Intent with the right action and data. In this example, we are going to send an email from our app by using an Intent object that launches existing email clients.
 
 
 
 
 
 
For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SDK 4.4

1. Create a New Android Application Project

Open Eclipse IDE and go to File → New → Project → Android Application Project.

Fill in the name of the application, the project and the package in the appropriate fields and then click Next.

sendEmailProj1

In the next window, check the “Create Activity” option. The new created activity will be the main activity of your project. Then press Next button.

sendEmailProj2

In “Configure Launcher Icon” window you should choose the icon you want to have in your app. We will use the default icon of android, so click Next.

createProject3!

Select the “Blank Activity” option and press Next.

createProject4!

Specify a name for the new Activity and a name for the layout description of your app. The .xml file for the layout will automatically be created in the res/layout folder. Finally, press Finish.

createProject5!

The picture below shows the structure of the created project.

structureSendEmailProj

2. Create the layout of the Main Activity

We want to send an email via our application, so we will use some EditTexts, where the user can fill in the necessary fields for an email creation. Also, we are going to use a Button, that enables the Intent when it is clicked.

Open res/layout/activity_main.xml file and go to the respective xml tab. Then paste the following.

activity_main.xml:

01 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
02    android:layout_width="fill_parent"
03    android:layout_height="fill_parent"
04    android:orientation="vertical" >
05  
06     <TextView
07         android:id="@+id/text1"
08         android:layout_width="fill_parent"
09         android:layout_height="wrap_content"
10         android:layout_marginBottom="20dp"
11         android:gravity="center"
12         android:text="Complete the fields to send an email"
13         android:textAppearance="?android:attr/textAppearanceMedium" />
14      
15    <EditText
16        android:id="@+id/recipient"
17        android:layout_width="match_parent"
18        android:layout_height="wrap_content"
19        android:ems="10"
20        android:inputType="textEmailAddress"
21        android:hint="Recipient" />
22  
23    <EditText
24        android:id="@+id/subject"
25        android:layout_width="match_parent"
26        android:layout_height="wrap_content"
27        android:ems="10"
28        android:hint="Subject" />
29  
30    <EditText
31        android:id="@+id/body"
32        android:layout_width="match_parent"
33        android:layout_height="wrap_content"
34        android:ems="10"
35        android:hint="Message body" />
36  
37    <Button
38        android:id="@+id/sendEmail"
39        android:layout_width="fill_parent"
40        android:layout_height="wrap_content"
41        android:layout_marginTop="30dp"
42        android:text="Compose an email" />
43      
44 </LinearLayout>

3. Code the Main Activity

As we already mentioned we need an Activity, which contains an Intent and launches the email clients that are installed in the Android device. For this reason, we should define SENDTO as action in that Intent and mailto: as it’s data. Moreover, we ought to set the Intent’s type as message/rfc822, in order to prompt only email providers. Another option for type could be text/plain, but this choice would launch and other clients that we don’t want in this app, such as Messaging.

In addition, Android provides us some further fields that can be used to complete some elements of an email client (for instance recipients, subject etc). These fields have to be attached to the Intent as extra data:

  • EXTRA_BCC: email addresses for blind carbon copy
  • EXTRA_CC: email addresses for carbon copy
  • EXTRA_EMAIL: email addresses for recipients
  • EXTRA_HTML_TEXT: supply an alternative to EXTRA_TEXT as HTML formatted text
  • EXTRA_STREAM: URI holding a stream of data supplying the data that are sent
  • EXTRA_SUBJECT: the subject of an email
  • EXTRA_TEXT: the message body of the email
  • EXTRA_TITLE: the title that is shown when the user has to choose an email client

In our application, we use EXTRA_EMAILEXTRA_SUBJECT and EXTRA_TEXT to fill in the appropriate fields in the email client.

Open src/com.javacodegeeks.android.sendemailtest/MainActivity.java and paste the following.

MainActivity.java:

01 package com.javacodegeeks.android.sendemailtest;
02  
03 import android.net.Uri;
04 import android.os.Bundle;
05 import android.app.Activity;
06 import android.content.Intent;
07 import android.view.View;
08 import android.widget.Button;
09 import android.widget.EditText;
10 import android.widget.Toast;
11  
12 public class MainActivity extends Activity {
13  
14     private EditText recipient;
15     private EditText subject;
16     private EditText body;
17      
18    @Override
19    protected void onCreate(Bundle savedInstanceState) {
20       super.onCreate(savedInstanceState);
21       setContentView(R.layout.activity_main);
22  
23       recipient = (EditText) findViewById(R.id.recipient);
24       subject = (EditText) findViewById(R.id.subject);
25       body = (EditText) findViewById(R.id.body);
26        
27       Button sendBtn = (Button) findViewById(R.id.sendEmail);
28       sendBtn.setOnClickListener(new View.OnClickListener() {
29          public void onClick(View view) {
30              sendEmail();
31              // after sending the email, clear the fields
32              recipient.setText("");
33              subject.setText("");
34              body.setText("");
35          }
36    });
37  
38    }
39    protected void sendEmail() {
40  
41       String[] recipients = {recipient.getText().toString()};
42       Intent email = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
43       // prompts email clients only
44       email.setType("message/rfc822");
45  
46       email.putExtra(Intent.EXTRA_EMAIL, recipients);
47       email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
48       email.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
49  
50       try {
51         // the user can choose the email client
52          startActivity(Intent.createChooser(email, "Choose an email client from..."));
53       
54       catch (android.content.ActivityNotFoundException ex) {
55          Toast.makeText(MainActivity.this"No email client installed.",
56                  Toast.LENGTH_LONG).show();
57       }
58    }
59     
60 }

4. Run the application

To run our application, right click on our project → Run as → Android Application. The AVD will appear with the app loaded, as shown in the picture.

AVDSendEmail1

Lets fill in all the fields and press the button “Compose an email”.

AVDSendEmail2

The default Email app of Android will launch, and the fields are filled in by the elements that we gave before, as you can see in the image below. If a problem occurs, you have to set up an account to the emulator.

AVDSendEmail3

To send the email press the arrow at the top-right of the above screen.

It is good to mention that in the emulator there aren’t any other email clients, so the user can not choose a different one. If we run the app in our Android device, all existed email providers will appear (such as Gmail etc) so the user will have the option to choose another one.

Download Eclipse Project

This was an example of sending an email in Android. Download the Eclipse Project of this example: SendEmailTest.zip

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s