Android Sending Email

thankyoudribble

Sending email from the android app is necessary task. It helps your users to easily contact you.

Advertisement

For sending email we will use our app to share data to mail client.(like Gmail android app).

The Intent object in android with proper action (ACTION_SEND) and data will help us to launch the available email clients to send an email in our application.

java
Intent emailIntent = new Intent(Intent.ACTION_SEND);

In android, Intent is a messaging object which is used to request an action from another app component such as activities, services, broadcast receivers and content providers.

To send an email you need to specify mailto: as URI using setData() method and data type will be to text/plain using setType() method as follows −

java
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL  , new String[]{"androidlearner@androidlearner.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT   , "Message Body");

Below is the sample code to send the mail.

call this method inside class extending activity

java
 public void sendEmail() {

      String[] TO = {"test@gmail.com","user2@yahoo.com"};
      String[] CC = {""};
      Intent emailIntent = new Intent(Intent.ACTION_SEND);

      emailIntent.setData(Uri.parse("mailto:"));
      emailIntent.setType("text/plain");
      emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
      emailIntent.putExtra(Intent.EXTRA_CC, CC);
      emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
      emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");

      try {
         startActivity(Intent.createChooser(emailIntent, "Send mail..."));
         finish();
         Log.i("Finished sending email...", "");
      } catch (android.content.ActivityNotFoundException ex) {
         Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
      }
   }