Android Basic Training Course: Sending Email with Intent

 
    In Android development, user can send Emails within our own app by using Intent. This quick tip shows you how to launch the built-in Mail application, supply it with data, and allow the user to send an email message. You will achieve this by creating and configuring the appropriate Intent within an application’s Activity.
    Before starting this sample project, you must know that we will send Email through Intent, it is carrying data from one component to another component with-in the application or outside the application.
    To send an email from your application, you can use an existing email client in your device like the default Email app (provide by Android OS System), Gmail (official app written by Google), Outlook (Microsoft email client),... For this purpose, we need to write an Activity that launches an email client (user can choose one of them above), using an implicit Intent with the right action and data, after all, the email was sent by this selected email client!
    DEMO VIDEO:

Creating the Intent

     The Intent which will be used to send email is android.content.intent.ACTION_SEND. This code below is creating this Intent instance:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

Configuring Intent Object - set Data type

    To send an email you need to specify mailto: an Uri using setType() method as follows:
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

Put Message Content through Intent

    After steps above, we have finished setup the Intent.ACTION_SEND. Now, the necessary work is configures the extras, and launches the email client Activity:
            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{getText(txtTo)});
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, getText(txtSubject));
            emailIntent.putExtra(Intent.EXTRA_TEXT, getText(txtContent));

            try {
                startActivity(Intent.createChooser(emailIntent, "Send mail..."));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
            }
    Details of features above:
  • EXTRA_EMAIL: a string array which contains all recipients.
  • EXTRA_SUBJECT: a constant String holding the desired subject line of a message.
  • EXTRA_TEXT: content of your email (String format).
    With using Intent.createChooser(), Android will show a popup that contains all available apps can send the mail in your device, user can choose a suitable one:

Sample Project

    I will provide a full demo project about this, the Intent.ACTION_SEND will be created and invoked after click a button in options menu (locate on Action Bar of the Activity). First, declaring an Activity layout (XML) file:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="info.devexchanges.sendingemailsample.MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.3"
            android:text="@string/to" />
 
        <EditText
            android:id="@+id/email"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7"
            android:inputType="textEmailAddress" />
 
    </LinearLayout>
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.3"
            android:text="@string/subject" />
 
        <EditText
            android:id="@+id/subject"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7"
            android:inputType="text" />
 
    </LinearLayout>
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:orientation="vertical">
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/content" />
 
        <EditText
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"/>
 
    </LinearLayout>
</LinearLayout>
    Create a menu file in res/menu folder like this:
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
 
    <item
        android:id="@+id/send"
        android:icon="@mipmap/ic_send"
        android:title="@string/app_name"
        app:showAsAction="always" />
</menu>
    Menu preview:
    In the Activity programmatically code, locate options menu file and set data for "Email Intent" through EditTexts, check Email is valid by regular expression,...:
MainActivity.java
package info.devexchanges.sendingemailsample;
 
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    private EditText txtTo;
    private EditText txtSubject;
    private EditText txtContent;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        txtContent = (EditText) findViewById(R.id.content);
        txtSubject = (EditText) findViewById(R.id.subject);
        txtTo = (EditText) findViewById(R.id.email);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
 
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.send) {
            sendingEmail();
 
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
 
    private String getText(EditText textView) {
        return textView.getText().toString().trim();
    }
 
    private void sendingEmail() {
        if (!checkEmailAddress(getText(txtTo))) {
            Toast.makeText(this, "Receiver Email is invalid!", Toast.LENGTH_SHORT).show();
        } else if (getText(txtSubject).equals("")) {
            Toast.makeText(this, "Please input Email Subject!", Toast.LENGTH_SHORT).show();
        } else {
            Intent emailIntent = new Intent(Intent.ACTION_SEND);
 
            emailIntent.setData(Uri.parse("mailto:"));
            emailIntent.setType("text/plain");
            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{getText(txtTo)});
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, getText(txtSubject));
            emailIntent.putExtra(Intent.EXTRA_TEXT, getText(txtContent));
 
            try {
                startActivity(Intent.createChooser(emailIntent, "Send mail..."));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
            }
        }
    }
 
    private boolean checkEmailAddress(String emailAddress) {
 
        String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Boolean b = emailAddress.matches(EMAIL_REGEX);
 
        return b;
    }
}
     When running app, we will have this screen:
    After click SEND Button and select Gmail when app-selection popup is shown, this Activity will launched:
    Android System will redirect to our app after send the email:
    If your mail was sent successful, it will available in the recipient Inbox:

Conclusions

    With using Intent, we will send a Message or Email easily. The user still has ultimate control on whether or not to send the message. The fact that this feature can be very useful for applications wishing to include simple user feedback functionality or to integrate tightly with the user’s preferred email client.
    In this post, I use OptionsMenu in Android SDK, you can see my previous chapter to see details. And finally, you can get this project code on @Github.



Share


Previous post
« Prev Post
Next post
Next Post »