首页 > 解决方案 > 如何捕获图像并通过电子邮件将其 Uri 直接发送到附件

问题描述

我有 Ui,我必须在其中捕获图像和 onActivityResult 我必须将其直接发送到电子邮件,因为我已经尝试了堆栈上的所有可能解决方案,但每次都失败并且它给我无法附加错误,经过很长时间搜索和实施的时间我发现了一些要检查的东西,如果我可以读取文件或者不是这样file.canRead(),它总是给我错误的。任何解决方案将不胜感激。

private fun sendEmail(liscence: String, desc: String) {`<br>
val emailIntent = Intent(Intent.ACTION_SEND)`<br>
        val to = arrayOf("info@gmail.com")`<br>
        emailIntent.putExtra(Intent.EXTRA_EMAIL, to)`

        emailIntent.type = "text/plain";
        emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        // attachment Uri comes through camera
        emailIntent.putExtra(Intent.EXTRA_STREAM, imagePath)
        // the mail subject
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report")
        //email body
        val body = "${liscence} \n ${desc}"
        emailIntent.putExtra(Intent.EXTRA_TEXT, body)
        //need this to prompts email client only
        emailIntent.type = "message/rfc822";
        startActivity(Intent.createChooser(emailIntent, "Send email using..."))
    }

标签: javaandroidkotlin

解决方案


这里经过大量研究,我在Android文档中找到了解决方案

https://developer.android.com/reference/android/support/v4/content/FileProvider.html#GetUri

这是我将捕获的图像共享到 Gmail 的最终代码。

此代码将直接转到 Manifest 文件,您必须将权限用作有效的权限提供者。

 <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.com.mydomain.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true"
        tools:replace="android:authorities">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/picker_provider_paths" />
    </provider>

提供者的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="image_picked" path="picked/"/>
<external-path name="*" path="Pictures/"/>
</paths>

将图像作为附件发送的函数。

    private fun sendEmail() {
    val contentUri = 
    FileProvider.getUriForFile(context!!,
            "yourPackageAndThen.com.mydomain.fileprovider", 
    File(PATH OF IMAGE or FILE ));

    val emailIntent = Intent(Intent.ACTION_SEND)

    //need this to prompts email client only
    emailIntent.type = "message/rfc822";
    val to = arrayOf("EMAIL ID TO SEND")
    emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

    // attachment Uri comes through camera
    emailIntent.putExtra(Intent.EXTRA_STREAM, contentUri)

    // the mail subject
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report")
    //email body
    emailIntent.putExtra(Intent.EXTRA_TEXT, MESSAGEforBody)
    startActivity(Intent.createChooser(emailIntent, "Send email using..."))

}

推荐阅读