Android将图片附加到电子邮件不起作用

时间:2013-08-19 10:29:57

标签: android android-intent

我正在尝试使用它的徽标从我的应用程序发送电子邮件 但是当我以字符串格式(应该是png)附件时收到电子邮件 我的代码:

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("application/image");

    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.fb_share_description));
    intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://my.package/" + R.drawable.ic_launcher));
   Intent chooser = Intent.createChooser(intent, "share");
   startActivity(chooser);

我该怎么办?

1 个答案:

答案 0 :(得分:8)

您无法通过内部资源将文件附加到电子邮件中。您必须先将其复制到存储的常用区域,如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是无法访问的URI。