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

问题描述

我正在尝试将附件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" />

代码

   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();
    }

}

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

for Yahoo Mail: "The attachment is too big to send"
for Gmail: "Permission denied for the attachment"

enter image description here

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

解决方法

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

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

Mail Gun Sendgrid是不错的选择