我正在测试创建.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();
}
}
这一切似乎都正常.它打开电子邮件客户端,主题,正文和附件都可见
并发送就好了,表明有附件
但是当我打开gmail时,没有显示附件
当我查看电子邮件时,同样的故事
从“已发送”文件夹中查看电话中的电子邮件,也显示没有附件
该代码是从SO上多个不同帖子中复制并粘贴的,看来他们没有任何问题.文件要去哪里?它被gmail阻止了吗?还是根本不发送?该文件不存在吗?
注意:我确实有< uses-permission android:name =“ android.permission.WRITE_EXTERNAL_STORAGE” />在清单中设置.
提前致谢.
解决方法:
问题出在文件路径上.进行了以下更改:
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();
}
}