Using Android Intent.ACTION_SEND for sending email

前端 未结 17 1261
野趣味
野趣味 2020-11-29 23:07

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

17条回答
  •  时光取名叫无心
    2020-11-29 23:43

    [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[]{"address@mail.com"});
        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);
    }
    

提交回复
热议问题