Sending an email with attachments programmatically on Android

前端 未结 3 1737
遇见更好的自我
遇见更好的自我 2020-12-09 10:17

I wish to implement a button that upon pressing it will open the default email client with an attachment file.

I am following this, but am getting an error message o

相关标签:
3条回答
  • 2020-12-09 10:28

    I think your problem is that you are not using the correct file path.

    The following works for me:

    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setType("text/plain");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"email@example.com"});
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "body text");
    File root = Environment.getExternalStorageDirectory();
    String pathToMyAttachedFile = "temp/attachement.xml";
    File file = new File(root, pathToMyAttachedFile);
    if (!file.exists() || !file.canRead()) {
    return;
    }
    Uri uri = Uri.fromFile(file);
    emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
    startActivity(Intent.createChooser(emailIntent, "Pick an Email provider"));
    

    You also need to give the user permission via a manifest file like below

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    0 讨论(0)
  • 2020-12-09 10:29

    Try to use this.It is working...

    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
                        emailIntent.setType("*/*");
    
                        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(listVideos.get(position).getVideoPath())));//path of video 
                        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    

    Thanks

    0 讨论(0)
  • 2020-12-09 10:39

    For newer devices you will encounter FileUriExposedException. Here is how to avoid it in Kotlin.

    val file = File(Environment.getExternalStorageDirectory(), "this")
    val authority = context.packageName + ".provider"
    val uri = FileProvider.getUriForFile(context, authority, file)
    val emailIntent = createEmailIntent(uri)
    startActivity(Intent.createChooser(emailIntent, "Send email..."))
    
    private fun createEmailIntent(attachmentUri: Uri): Intent {
        val emailIntent = Intent(Intent.ACTION_SEND)
        emailIntent.type = "vnd.android.cursor.dir/email"
        val to = arrayOf("some@email.com")
        emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
        emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri)
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject")
        return emailIntent
    }
    
    0 讨论(0)
提交回复
热议问题