如何通过电子邮件将文本文件作为附件发送 - Android?

How to send text file via email as an attachment - Android?

我在网上看了很多代码,但似乎都运行出了问题。

使用以下函数创建并保存文件:

    private static String filename = "eulerY.txt" ;

    private void saveData() {

      

        FileOutputStream fos_FILE_eulerY = null;

        String message = "hello";
        try {
            fos_FILE_eulerY = openFileOutput(filename , MODE_PRIVATE);
            fos_FILE_eulerY.write(message.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos_FILE_eulerY != null) {
                try {
                    fos_FILE_eulerY.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        // export data
        sendEmail ();
    }

但是,当 运行ning 下面的代码发送文件时,我一直 运行ning 进入问题 ClipData.Item.getUri 并且按照建议使用此 link“ Gmail 时,它显示“无法附加文件”

    private void sendEmail (){
        File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
        Uri path = Uri.fromFile(filelocation);
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
       // set the type to 'email'
        emailIntent .setType("vnd.android.cursor.dir/email");
        String to[] = {"asd@gmail.com"};
        emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
      // the attachment
        emailIntent .putExtra(Intent.EXTRA_STREAM, path);
      // the mail subject
        emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
        startActivity(Intent.createChooser(emailIntent , "Send email..."));
    }


如果有什么方法可以发送此文件,我将不胜感激。

如果您的 targetSdkVersion >= 24,那么我们必须使用 FileProvider class 来授予对特定文件或文件夹的访问权限,以便其他应用可以访问它们。

第一步:AndroidManifest.xml 文件中添加以下代码。

        <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

第 2 步

res 文件夹中创建一个 xml 文件夹。并创建一个名为 file_paths.xml 的文件,因为在 <meta-data>.

中查看上面的代码

file_paths.xml

<paths>
    <external-path name="external_files" path="."/>
</paths>

第 3 步 现在您可以将文件保存在 package.private 文件夹中,并且可以将保存在此文件夹中的 file uri 共享给其他应用程序,例如 gmail 应用程序作为 attachment。现在你的方法看起来像:

    private void saveData() {
    String filename = "eulerY.txt" ;
    //FileOutputStream fos_FILE_eulerY = null;
    File externalFilesDirectory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
    File textFile = new File(externalFilesDirectory,filename);
    String message = "hello";
    try {
        //fos_FILE_eulerY = openFileOutput(textFile.getAbsolutePath() , MODE_PRIVATE);
        //fos_FILE_eulerY.write(message.getBytes());
        FileWriter writer = new FileWriter(textFile);
        writer.append(message);
        writer.flush();
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e){
        e.getLocalizedMessage();
    }


    // export data
    sendEmail (textFile);
}

    private void sendEmail (File file){
    //File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
    //Uri path = Uri.fromFile(filelocation);
    //FileProvider.getUriForFile(it, "${it.packageName}.provider", file)
    Uri fileUri = FileProvider.getUriForFile(this,getPackageName()+".provider",file);
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    // set the type to 'email'
    emailIntent .setType("vnd.android.cursor.dir/email");
    String[] to = {"asd@gmail.com"};
    emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
    // the attachment
    emailIntent .putExtra(Intent.EXTRA_STREAM, fileUri);
    // the mail subject
    emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
    startActivity(Intent.createChooser(emailIntent , "Send email..."));
}