Android,.txt电子邮件附件不通过意图发送

时间:2015-07-31 19:06:35

标签: android email android-intent gmail filewriter

我正在测试创建.txt文件,然后通过意图将其作为电子邮件附件发送。

创建.txt文件

    try {
        String fileName = "testFileName.txt";
        File root = new File(Environment.getExternalStorageDirectory(), "testDir");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, fileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append("Testing email txt attachment.");
        writer.flush();
        writer.close();
        sendEmail(gpxfile.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }

发送电子邮件

protected void sendEmail(String fileName){
    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_SUBJECT, "Test subject");
    i.putExtra(Intent.EXTRA_TEXT, "This is the body of the email");
    i.putExtra(Intent.EXTRA_STREAM, Uri.parse(fileName));
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
}

这一切似乎都很好。它打开了电子邮件客户端,主题,正文和附件都可见

Composing email

发送得很好,表明有附件

Sent email

但是当我打开gmail时,没有显示附件

Gmail, no attachment

查看电子邮件时的情况相同

Gmail, detailed, no attachment

在“已发送”文件夹中查看手机上的电子邮件,也显示无附件

Android, sent, no attachment

代码是SO上的多个不同帖子的复制和粘贴,看起来他们没有任何问题。文件在哪里?它被gmail阻止了吗?或者根本不发送?该文件不存在吗?

注意:我在清单中设置了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

提前致谢。

1 个答案:

答案 0 :(得分:3)

The problem was with the file path. Made the following changes:

sendEmail(gpxfile); // This is the file itself, not the file path

Then actually sending the email:

protected void sendEmail(File file){
    Uri path = Uri.fromFile(file); // This guy gets the job done!

    Intent i = new Intent(Intent.ACTION_SEND);
    i.setType("message/rfc822");
    i.putExtra(Intent.EXTRA_SUBJECT, "Test subject");
    i.putExtra(Intent.EXTRA_TEXT, "This is the body of the email");
    i.putExtra(Intent.EXTRA_STREAM, path); // Include the path
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }
}