简体   繁体   中英

Android send email with attachments using only email apps

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... ie 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM