【问题标题】:Android - Sending TXT File as Attachment to Email Fails ("Couldn't send attachment")Android - 将 TXT 文件作为电子邮件附件发送失败(“无法发送附件”)
【发布时间】:2013-04-12 01:00:16
【问题描述】:

我正在尝试让我的 Android 应用程序发送附有文件的电子邮件,并且我从 .txt 文件开始,因为这些很简单。

到目前为止,我有这个(发生在片段中):

//Send the email
Intent mailIntent = new Intent(Intent.ACTION_SEND);
mailIntent.setType("text/Message");
mailIntent.putExtra(Intent.EXTRA_EMAIL  , new String[]{address});
mailIntent.putExtra(Intent.EXTRA_SUBJECT, "Test Email");
mailIntent.putExtra(Intent.EXTRA_TEXT   , "Hi!  This is a test!");

//Deal with the attached report
String FileName = "report.txt";
Calculator.generateReport(getActivity().getApplicationContext(), FileName);
//It will be called "report.txt"
File attachment = getActivity().getApplicationContext().getFileStreamPath(FileName);
if (!attachment.exists() || !attachment.canRead()) {
    Toast.makeText(getActivity().getApplicationContext(), 
                   "Attachment Error", 
                   Toast.LENGTH_SHORT).show();
    System.out.println("ATTACHMENT ERROR");
}
else
{
    Uri uri = Uri.fromFile(attachment);
    mailIntent.putExtra(Intent.EXTRA_STREAM, uri);
}

//Send, if valid!
try {
   startActivity(Intent.createChooser(mailIntent, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(getActivity().getApplicationContext(), 
               "There are no email clients installed.", 
               Toast.LENGTH_SHORT).show();
}

不幸的是,这似乎不起作用。现在我知道该文件存在;如果我在generateReport() 之后插入适当的代码,我可以找到并访问该文件并读取其内容。它就在那里,而且我的名字是对的。

当我有选择电子邮件客户端的选项时,我选择了 Gmail,发现电子邮件中确实有一个 report.txt 文件。但是,当我发送电子邮件时,我收到一条通知,说明“无法发送附件”,并且电子邮件到达时没有任何附件。

请注意,我也尝试过其他 Intent 类型,例如 text/plainmessage/rfc822,但均无济于事。

关于我可能做错了什么有什么想法吗?

【问题讨论】:

    标签: java android email android-intent email-attachments


    【解决方案1】:

    如果您已将文件保存为应用程序的私有文件,应用程序可以查看是否正常,但外部电子邮件客户端将无法查看。

    您需要将其写入外部存储,或将其公开。

    使用http://developer.android.com/reference/android/content/Context.html#MODE_WORLD_READABLEhttp://developer.android.com/guide/topics/data/data-storage.html

    【讨论】:

    • 啊,是的,切换到MODE_WORLD_READABLE 有效!不幸的是,我看到它在 API 17 中已被弃用,并且写入外部而不是内部存储器(使用 context.getExternalFilesDir(null) 而不是 context.getFilesDir())似乎没有帮助;无论哪种方式,我都需要指定世界可读模式。有没有办法解决这个问题?
    • 看看直接写到外部存储:developer.android.com/guide/topics/data/…
    【解决方案2】:

    https://stackoverflow.com/a/18548685/293280

    上面的 SO 回答了一个非常好的复制文件、将其附加到电子邮件、发送电子邮件以及最后删除复制文件的演练。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2013-08-26
      • 2013-03-19
      • 1970-01-01
      相关资源
      最近更新 更多