Home > OS >  Android send email with attachments using only email apps
Android send email with attachments using only email apps

Time:05-18

The official docs show how you can send an email with an attachment:

public void composeEmail(String[] addresses, String subject, Uri attachment) {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("*/*");
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_STREAM, attachment);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

It then says:

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.

Like so:

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);
    }
}

But actually, I want a combination of the above... i.e. send an email with an attachment and using only an email app.

But when using intent.setData(Uri.parse("mailto:")) in combination with Intent.ACTION_SEND or Intent.ACTION_SEND_MULTIPLE, nothing happens... no email app (or app chooser) opens at all.

So how do I send an email with attachment (or multiple attachments) whilst also restricting the app to email apps?

CodePudding user response:

That mailto: URI string appears invalid without recipients; try something alike this instead:

intent.setData(Uri.parse("mailto:"   String.join(",", addresses)));

See RFC 6068: The 'mailto' URI Scheme.

CodePudding user response:

Remove if (intent.resolveActivity(getPackageManager()) != null) check and it will open the intent. Usually the OS returns null whether the email handling apps exist or not.

  • Related