我正在尝试让我的 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/plain
and message/rfc822
,但无济于事。
关于我可能做错了什么的任何想法?