3

我正在尝试让我的 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文件附加到电子邮件中。但是,当我发送电子邮件时,我会收到一条通知,说明“无法发送附件”,并且电子邮件到达时没有任何附件。

我应该注意,我也尝试过其他意图类型,例如text/plainand message/rfc822,但无济于事。

关于我可能做错了什么的任何想法?

4

2 回答 2

4

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

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

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

于 2013-04-12T01:06:21.107 回答
2

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

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

于 2013-12-05T05:50:41.247 回答