您不能从内部资源将文件附加到电子邮件。您必须先将其复制到存储的常用区域,例如 SD 卡。
InputStream in = null;
OutputStream out = null;
try {
in = getResources().openRawResource(R.drawable.ic_launcher);
out = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "image.png"));
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
e.printStackTrace();
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
//Send the file
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/html");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "File attached");
Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.png"));
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
这是必需的,因为您与应用程序捆绑的资源是只读的并且被沙箱化到您的应用程序中。电子邮件客户端收到的 URI 是它无法访问的。