Android,.txt 电子邮件附件未通过 Intent 发送

标签 android email android-intent gmail filewriter

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

创建 .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" />在 list 中设置。

提前致谢。

最佳答案

问题出在文件路径上。进行了以下更改:

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

然后实际发送邮件:

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

关于Android,.txt 电子邮件附件未通过 Intent 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31753423/

相关文章:

android - 在 Android 中发布 JSON 并检索响应

android - 弹出 showAtLocation 不起作用

android - 如何从不同的 Activity 访问 SQL 数据库?

android - 如何检测用户之间的切换

java - 在 IMAP 中创建文件夹不起作用

android - 如何转到android studio上的下一个随机 Activity ?

android - 为什么 Uri.getPath() 不返回实际路径?

php - 电子邮件跟踪 - Apple Mail

email - 发送带有头像的电子邮件

安卓 ActivityNotFoundException