Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

Using Android Intent.ACTION_SEND for sending email

I'm using Intent.ACTION_SEND to send an email. However, when I call the intent it is showing choices to send a message, send an email, and also to send via bluetooth. I want it to only show choices to send an email. How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

[Solution for API LEVEL >=15]

I've finally succeded in sending email WITH attachments to ONLY email clients. I write it here because it took me a lot of time and it may be usefull to others.

The problem is:

  • Intent.ACTION_SENDTO takes Data URI (so you can specify "mailto:" schema) BUT it does not accept Intent:EXTRA_STREAM.

  • Intent.ACTION_SEND accepts Intent:EXTRA_STREAM (so you can add attachment) BUT it takes only Type (not Data URI so you cannot specify "mailto:" schema).

So Intent.ACTION_SEND lets the user choose from several Activities, even if you setType("message/rfc822"), because that App/Activities can manage all file types (tipically GDrive/Dropbox Apps) and so even email message files.

The solution is in the setSelector method. With this method you can use Intent.ACTION_SENDTO to select the Activity, but then send the Intent.ACTION_SEND Intent.

Here my solution code (the attachment came from a FileProvider, but it could be any file):

{
    Intent emailSelectorIntent = new Intent(Intent.ACTION_SENDTO);
    emailSelectorIntent.setData(Uri.parse("mailto:"));

    final Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    emailIntent.setSelector( emailSelectorIntent );

    Uri attachment = FileProvider.getUriForFile(this, "my_fileprovider", myFile);
    emailIntent.putExtra(Intent.EXTRA_STREAM, attachment);

    if( emailIntent.resolveActivity(getPackageManager()) != null )
        startActivity(emailIntent);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...