Pit
Pit

Reputation: 1

Why doesn't hand over a file for a function of sending an email with attachment in Kotlin

I have a problem with my code. The file exists on the right path, like the toast message. And the chooser show me also my file name. But when I choose an email app, I receive an error. One app show "error at the coping of" and the other "file cannot attached".

My function for send email to a mail app

private fun sendEmail() {
        try {
            fileName = "exported_Data.csv"
            val externalStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            val exportDirPath = File(externalStorageDir, "exports")
            file = File(exportDirPath,  fileName)
            if (file.exists()) {
                Toast.makeText(this, "file exists", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(this, "file doesn't exists", Toast.LENGTH_LONG).show()
            }
           
            val uri = FileProvider.getUriForFile(this, "com.example.test_send_email.fileprovider", file)
   
            email = etEmail.text.toString()
            subject = etSubject.text.toString()
            message = etMessage.text.toString()
            val emailIntent = Intent(Intent.ACTION_SEND)
            emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            emailIntent.setDataAndType(uri, "application/octet-stream")
            emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
            emailIntent.putExtra(Intent.EXTRA_STREAM, uri)
            emailIntent.putExtra(Intent.EXTRA_TEXT, message)
            emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(Intent.createChooser(emailIntent, "Sending email..."))
        }
        catch (t: Throwable) {
            Toast.makeText(this, "failed: $t", Toast.LENGTH_LONG).show()
                                          //Request failed try again:
        }
    }

The Snippet from the AndroidManifest:

 </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.test_send_email.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

and this is the file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>

I have tried the EXTRA_STREAM with uri.parse(filename), but also the same. I don't if there a rights problem.

UPDATE: Send to gmail works, but not to other email apps.

Upvotes: 0

Views: 18

Answers (0)

Related Questions