Json 文件未附加到 android 的电子邮件

mr *_*oob 5 java android email-attachments

我正在尝试将附加的 json 文件发送到电子邮件,但是由于某种原因,在发送/创建电子邮件时未附加 json 文件。注意:我不希望用户选择要附加的文件,我希望它自动固定/设置。

我有以下权限 AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Run Code Online (Sandbox Code Playgroud)

和代码

   private void backupJsonToEmail(String jsonString) {
    // create file

    if(!getFilesDir().exists()){
        getFilesDir().mkdir();
    }
    String filePath = getFilesDir() + File.separator + BACKUP_NAME;
    System.out.println("file path: " + filePath);
    // /data/user/0/com.my.stuff/files/backup.json

    try {
        FileOutputStream fos = new FileOutputStream(filePath);
        DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
        outStream.writeBytes(jsonString);
        outStream.close();

        // send to email
        try {
            File file = new File(filePath);
            long fileKbSize = file.length() / 1024;
            System.out.println("FILE SIZE IS: " + fileKbSize + " kb"); // 69 kb...

            Uri uri = Uri.fromFile(file);
            String to[] = {"test@yahoo.com"};

            Intent originalIntent = ShareCompat.IntentBuilder.from(this)
                    .setType("application/json")
                    .setEmailTo(to)
                    .setStream(uri)
                    .setSubject("test")
                    .setText("here is the attached json")
                    .getIntent();
            originalIntent.setData(Uri.parse("mailto:"));
            originalIntent.setAction(Intent.ACTION_SENDTO);

            Intent finalIntent = Intent.createChooser(originalIntent, "choose an email application");
            startActivity(finalIntent);

        } catch (Throwable t) {
            Toast.makeText(this, "Request failed try again: " + t.toString(), Toast.LENGTH_LONG).show();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}
Run Code Online (Sandbox Code Playgroud)

EDIT1:在进行@piyushpk 建议的建议更改后,我现在在选择电子邮件应用程序时遇到以下错误:

for Yahoo Mail: "The attachment is too big to send"
for Gmail: "Permission denied for the attachment"
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但是,根据我的打印声明,文件大小仅为 69 kb...

Jin*_*kur 0

我认为您正在尝试使用内置电子邮件应用程序发送 json 文件,而 yahoo 正在抱怨大小,而 Gmail 则否认它,因为 json 被认为不是安全扩展。

相反,使用一些 SMTP 电子邮件 api(例如发送网格等)来发送文件,而无需任何内置 Android 应用程序。 https://github.com/sendgrid/sendgrid-java

Mail Gun Sendgrid 是不错的选择