How to send emails from my Android application?

AndroidEmail

Android Problem Overview


I am developing an application in Android. I don't know how to send an email from the application?

Android Solutions


Solution 1 - Android

The best (and easiest) way is to use an Intent:

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT   , "body of email");
try {
	startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
	Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

Otherwise you'll have to write your own client.

Solution 2 - Android

Use .setType("message/rfc822") or the chooser will show you all of the (many) applications that support the send intent.

Solution 3 - Android

I've been using this since long time ago and it seems good, no non-email apps showing up. Just another way to send a send email intent:

Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject of email");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:[email protected]")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);

Solution 4 - Android

I was using something along the lines of the currently accepted answer in order to send emails with an attached binary error log file. GMail and K-9 send it just fine and it also arrives fine on my mail server. The only problem was my mail client of choice Thunderbird which had troubles with opening / saving the attached log file. In fact it simply didn't save the file at all without complaining.

I took a look at one of these mail's source codes and noticed that the log file attachment had (understandably) the mime type message/rfc822. Of course that attachment is not an attached email. But Thunderbird cannot cope with that tiny error gracefully. So that was kind of a bummer.

After a bit of research and experimenting I came up with the following solution:

public Intent createEmailOnlyChooserIntent(Intent source,
	CharSequence chooserTitle) {
	Stack<Intent> intents = new Stack<Intent>();
	Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
	        "[email protected]", null));
	List<ResolveInfo> activities = getPackageManager()
	        .queryIntentActivities(i, 0);

	for(ResolveInfo ri : activities) {
	    Intent target = new Intent(source);
	    target.setPackage(ri.activityInfo.packageName);
	    intents.add(target);
	}

	if(!intents.isEmpty()) {
	    Intent chooserIntent = Intent.createChooser(intents.remove(0),
	            chooserTitle);
	    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
	            intents.toArray(new Parcelable[intents.size()]));

	    return chooserIntent;
	} else {
	    return Intent.createChooser(source, chooserTitle);
	}
}

It can be used as follows:

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("*/*");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(crashLogFile));
i.putExtra(Intent.EXTRA_EMAIL, new String[] {
	ANDROID_SUPPORT_EMAIL
});
i.putExtra(Intent.EXTRA_SUBJECT, "Crash report");
i.putExtra(Intent.EXTRA_TEXT, "Some crash report details");

startActivity(createEmailOnlyChooserIntent(i, "Send via email"));

As you can see, the createEmailOnlyChooserIntent method can be easily fed with the correct intent and the correct mime type.

It then goes through the list of available activities that respond to an ACTION_SENDTO mailto protocol intent (which are email apps only) and constructs a chooser based on that list of activities and the original ACTION_SEND intent with the correct mime type.

Another advantage is that Skype is not listed anymore (which happens to respond to the rfc822 mime type).

Solution 5 - Android

To JUST LET EMAIL APPS to resolve your intent you need to specify ACTION_SENDTO as Action and mailto as Data.

private void sendEmail(){

	Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
	emailIntent.setData(Uri.parse("mailto:" + "[email protected]")); // You can use "mailto:" if you don't know the address beforehand.
	emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My email's subject");
	emailIntent.putExtra(Intent.EXTRA_TEXT, "My email's body");
	
	try {
	    startActivity(Intent.createChooser(emailIntent, "Send email using..."));
	} catch (android.content.ActivityNotFoundException ex) {
	    Toast.makeText(Activity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
	}

}

Solution 6 - Android

The solution to this is simple: the android documentation explains it.

(https://developer.android.com/guide/components/intents-common.html#Email)

The most important is the flag: it is ACTION_SENDTO, and not ACTION_SEND

The other important line is

intent.setData(Uri.parse("mailto:")); ***// only email apps should handle this***

By the way, if you send an empty Extra, the if() at the end won't work and the app won't launch the email client.

According to Android documentation. If you want to ensure that your intent is handled only by an email app (and not other text messaging or social apps), then use the ACTION_SENDTO action and include the "mailto:" data scheme. For example:

public void composeEmail(String[] addresses, String subject) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

Solution 7 - Android

The strategy of using .setType("message/rfc822") or ACTION_SEND seems to also match apps that aren't email clients, such as Android Beam and Bluetooth.

Using ACTION_SENDTO and a mailto: URI seems to work perfectly, and [is recommended in the developer documentation][1]. However, if you do this on the official emulators and there aren't any email accounts set up (or there aren't any mail clients), you get the following error:

>Unsupported action > >That action is not currently supported.

As shown below:

![Unsupported action: That action is not currently supported.][2]

It turns out that the emulators resolve the intent to an activity called [com.android.fallback.Fallback][3], which displays the above message. [Apparently this is by design.][4]

If you want your app to circumvent this so it also works correctly on the official emulators, you can check for it before trying to send the email:

private void sendEmail() {
	Intent intent = new Intent(Intent.ACTION_SENDTO)
		.setData(new Uri.Builder().scheme("mailto").build())
		.putExtra(Intent.EXTRA_EMAIL, new String[]{ "John Smith <[email protected]>" })
		.putExtra(Intent.EXTRA_SUBJECT, "Email subject")
		.putExtra(Intent.EXTRA_TEXT, "Email body")
	;

	ComponentName emailApp = intent.resolveActivity(getPackageManager());
	ComponentName unsupportedAction = ComponentName.unflattenFromString("com.android.fallback/.Fallback");
	if (emailApp != null && !emailApp.equals(unsupportedAction))
		try {
			// Needed to customise the chooser dialog title since it might default to "Share with"
			// Note that the chooser will still be skipped if only one app is matched
			Intent chooser = Intent.createChooser(intent, "Send email with");
			startActivity(chooser);
			return;
		}
		catch (ActivityNotFoundException ignored) {
		}

	Toast
		.makeText(this, "Couldn't find an email app and account", Toast.LENGTH_LONG)
		.show();
}

Find more info in [the developer documentation][1].

[1]: https://developer.android.com/guide/components/intents-common.html#Email "Compose an email with optional attachments" [2]: http://i.stack.imgur.com/wcbFj.png [3]: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/5.1.0_r1/com/android/fallback/Fallback.java [4]: https://groups.google.com/forum/#!topic/android-developers/gtf-phP67Iw "Curious about com.android.fallback.Fallback"

Solution 8 - Android

Sending email can be done with Intents which will require no configuration. But then it will require user interaction and the layout will be a bit restricted.

Build and sending a more complex email without user interaction entails building your own client. The first thing is that the Sun Java API for email are unavailable. I have had success leveraging the Apache Mime4j library to build email. All based on the docs at nilvec.

Solution 9 - Android

Here is the sample working code which opens mail application in android device and auto-filled with To address and Subject in the composing mail.

protected void sendEmail() {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:[email protected]"));
    intent.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

Solution 10 - Android

I use the below code in my apps. This shows exactly email client apps, such as Gmail.

    Intent contactIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.email_to), null));
    contactIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject));
    startActivity(Intent.createChooser(contactIntent, getString(R.string.email_chooser)));

Solution 11 - Android

This will show you only the email clients (as well as PayPal for some unknown reason)

 public void composeEmail() {

    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:"));
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    intent.putExtra(Intent.EXTRA_TEXT, "Body");
    try {
        startActivity(Intent.createChooser(intent, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
}

Solution 12 - Android

This is how I did it. Nice and simple.

String emailUrl = "mailto:[email protected]?subject=Subject Text&body=Body Text";
        Intent request = new Intent(Intent.ACTION_VIEW);
        request.setData(Uri.parse(emailUrl));
        startActivity(request);

Solution 13 - Android

This function first direct intent gmail for sending email, if gmail is not found then promote intent chooser. I used this function in many commercial app and it's working fine. Hope it will help you:

public static void sentEmail(Context mContext, String[] addresses, String subject, String body) {
    
    try {
        Intent sendIntentGmail = new Intent(Intent.ACTION_VIEW);
        sendIntentGmail.setType("plain/text");
        sendIntentGmail.setData(Uri.parse(TextUtils.join(",", addresses)));
        sendIntentGmail.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
        sendIntentGmail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentGmail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentGmail.putExtra(Intent.EXTRA_TEXT, body);
        mContext.startActivity(sendIntentGmail);
    } catch (Exception e) {
        //When Gmail App is not installed or disable
        Intent sendIntentIfGmailFail = new Intent(Intent.ACTION_SEND);
        sendIntentIfGmailFail.setType("*/*");
        sendIntentIfGmailFail.putExtra(Intent.EXTRA_EMAIL, addresses);
        if (subject != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_SUBJECT, subject);
        if (body != null) sendIntentIfGmailFail.putExtra(Intent.EXTRA_TEXT, body);
        if (sendIntentIfGmailFail.resolveActivity(mContext.getPackageManager()) != null) {
            mContext.startActivity(sendIntentIfGmailFail);
        }
    }
}

Solution 14 - Android

I used this code to send mail by launching default mail app compose section directly.

    Intent i = new Intent(Intent.ACTION_SENDTO);
    i.setType("message/rfc822"); 
    i.setData(Uri.parse("mailto:"));
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
    i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    i.putExtra(Intent.EXTRA_TEXT   , "body of email");
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

Solution 15 - Android

simple try this one

 public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	buttonSend = (Button) findViewById(R.id.buttonSend);
	textTo = (EditText) findViewById(R.id.editTextTo);
	textSubject = (EditText) findViewById(R.id.editTextSubject);
	textMessage = (EditText) findViewById(R.id.editTextMessage);

	buttonSend.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {

			String to = textTo.getText().toString();
			String subject = textSubject.getText().toString();
			String message = textMessage.getText().toString();

			Intent email = new Intent(Intent.ACTION_SEND);
			email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
			// email.putExtra(Intent.EXTRA_CC, new String[]{ to});
			// email.putExtra(Intent.EXTRA_BCC, new String[]{to});
			email.putExtra(Intent.EXTRA_SUBJECT, subject);
			email.putExtra(Intent.EXTRA_TEXT, message);

			// need this to prompts email client only
			email.setType("message/rfc822");

			startActivity(Intent.createChooser(email, "Choose an Email client :"));

		}
	});
}

Solution 16 - Android

Other solution can be

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("plain/text");
emailIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Yo");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi");
startActivity(emailIntent);

Assuming most of the android device has GMail app already installed.

Solution 17 - Android

Use this for send email...

boolean success = EmailIntentBuilder.from(activity)
    .to("[email protected]")
    .cc("[email protected]")
    .subject("Error report")
    .body(buildErrorReport())
    .start();

use build gradle :

compile 'de.cketti.mailto:email-intent-builder:1.0.0'

Solution 18 - Android

 Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
            "mailto","[email protected]", null));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Forgot Password");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "this is a text ");
    startActivity(Intent.createChooser(emailIntent, "Send email..."));

Solution 19 - Android

This method work for me. It open Gmail app (if installed) and set mailto.

public void openGmail(Activity activity) {
    Intent emailIntent = new Intent(Intent.ACTION_VIEW);
    emailIntent.setType("text/plain");
    emailIntent.setType("message/rfc822");
    emailIntent.setData(Uri.parse("mailto:"+activity.getString(R.string.mail_to)));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.app_name) + " - info ");
    final PackageManager pm = activity.getPackageManager();
    final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
    ResolveInfo best = null;
    for (final ResolveInfo info : matches)
        if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
            best = info;
    if (best != null)
        emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
    activity.startActivity(emailIntent);
}

Solution 20 - Android

/**
 * Will start the chosen Email app
 *
 * @param context    current component context.
 * @param emails     Emails you would like to send to.
 * @param subject    The subject that will be used in the Email app.
 * @param forceGmail True - if you want to open Gmail app, False otherwise. If the Gmail
 *                   app is not installed on this device a chooser will be shown.
 */
public static void sendEmail(Context context, String[] emails, String subject, boolean forceGmail) {

    Intent i = new Intent(Intent.ACTION_SENDTO);
    i.setData(Uri.parse("mailto:"));
    i.putExtra(Intent.EXTRA_EMAIL, emails);
    i.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (forceGmail && isPackageInstalled(context, "com.google.android.gm")) {
        i.setPackage("com.google.android.gm");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    } else {
        try {
            context.startActivity(Intent.createChooser(i, "Send mail..."));
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "No email app is installed on your device...", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 * Check if the given app is installed on this devuice.
 *
 * @param context     current component context.
 * @param packageName The package name you would like to check.
 * @return True if this package exist, otherwise False.
 */
public static boolean isPackageInstalled(@NonNull Context context, @NonNull String packageName) {
    PackageManager pm = context.getPackageManager();
    if (pm != null) {
        try {
            pm.getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    return false;
}

Solution 21 - Android

Try this:

String mailto = "mailto:[email protected]" +
    "?cc=" + "[email protected]" +
    "&subject=" + Uri.encode(subject) +
    "&body=" + Uri.encode(bodyText);

Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse(mailto));

try {
    startActivity(emailIntent);
} catch (ActivityNotFoundException e) {
    //TODO: Handle case where no email app is available
}

The above code will open the users favourite email client prefilled with the email ready to send.

Source

Solution 22 - Android

Kotlin version which only shows Email clients (no contacts etc.):

    with(Intent(Intent.ACTION_SEND)) {
        type = "message/rfc822"
        data = Uri.parse("mailto:")
        putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]"))
        putExtra(Intent.EXTRA_SUBJECT,"YOUR SUBJECT")
        putExtra(Intent.EXTRA_TEXT, "YOUR BODY")
        try {
            startActivity(Intent.createChooser(this, "Send Email with"))
        } catch (ex: ActivityNotFoundException) {
            // No email clients found, might show Toast here
        }
    }

Solution 23 - Android

The code below works on Android 10 devices and higher. It also sets the subject, body and recipient(To).

val uri = Uri.parse("mailto:$EMAIL")
                .buildUpon()
                .appendQueryParameter("subject", "App Feedback")
                .appendQueryParameter("body", "Body Text")
                .appendQueryParameter("to", EMAIL)
                .build()

            val emailIntent = Intent(Intent.ACTION_SENDTO, uri)

            startActivity(Intent.createChooser(emailIntent, "Select app"))

Solution 24 - Android

import androidx.core.app.ShareCompat
import androidx.core.content.IntentCompat

ShareCompat.IntentBuilder(this)
                .setType("message/rfc822")
                .setEmailTo(arrayOf(email))
                .setStream(uri)
                .setSubject(subject)
                .setText(message + emailMessage)
                .startChooser()

Solution 25 - Android

This is the most clean way of sending email on Android.

 val intent = Intent(Intent.ACTION_SENDTO).apply {
    data = Uri.parse("mailto:")
    putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]"))
    putExtra(Intent.EXTRA_SUBJECT, "Subject")
    putExtra(Intent.EXTRA_TEXT, "Email body")
}
if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
}

You also need to specify in your manifest (outside your application tag) the query for applications that handle email (mailto)

<queries>
    <intent>
        <action android:name="android.intent.action.SENDTO" />
        <data android:scheme="mailto" />
    </intent>
</queries>

If you need to send HTML text in the email body, please replace the "Email body" with your email string, something like this (please beware that Html.fromHtml maybe deprecated this was only for show you how to do it)

Html.fromHtml(
    StringBuilder().append("<b>Hello world</b>").toString()
)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRakeshView Question on Stackoverflow
Solution 1 - AndroidJeremy LoganView Answer on Stackoverflow
Solution 2 - AndroidJeff SView Answer on Stackoverflow
Solution 3 - AndroidRandy Sugianto 'Yuku'View Answer on Stackoverflow
Solution 4 - AndroidtiguchiView Answer on Stackoverflow
Solution 5 - AndroidwildzicView Answer on Stackoverflow
Solution 6 - AndroidPedro VarelaView Answer on Stackoverflow
Solution 7 - AndroidSamView Answer on Stackoverflow
Solution 8 - AndroidReneView Answer on Stackoverflow
Solution 9 - AndroidSridhar NalamView Answer on Stackoverflow
Solution 10 - AndroidlomzaView Answer on Stackoverflow
Solution 11 - AndroidA ParsView Answer on Stackoverflow
Solution 12 - AndroidDog LoverView Answer on Stackoverflow
Solution 13 - AndroidShohan Ahmed SijanView Answer on Stackoverflow
Solution 14 - AndroidFaris MuhammedView Answer on Stackoverflow
Solution 15 - AndroidNagarjunaReddyView Answer on Stackoverflow
Solution 16 - AndroidsilentsudoView Answer on Stackoverflow
Solution 17 - AndroidManishView Answer on Stackoverflow
Solution 18 - AndroidTousif AkramView Answer on Stackoverflow
Solution 19 - AndroidpsychoView Answer on Stackoverflow
Solution 20 - AndroidGal RomView Answer on Stackoverflow
Solution 21 - AndroidDan BrayView Answer on Stackoverflow
Solution 22 - AndroidMerthan ErdemView Answer on Stackoverflow
Solution 23 - AndroidRaphaelNdongaView Answer on Stackoverflow
Solution 24 - AndroidOmkar TView Answer on Stackoverflow
Solution 25 - AndroidAdelinoView Answer on Stackoverflow