mukesh
mukesh

Reputation: 4140

How to attach image in email from drawable in android

I am attaching an image from drawable folder and sending it in a email. when I send it from default email client.Image extension(.png) is missing in attachment and and also the file name is changed itself. I want t send image with default name(as in drawable) and with .png extension.

this is my code.

    Intent email = new Intent(Intent.ACTION_SEND);
            email.setType("image/png");

            email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });

            email.putExtra(Intent.EXTRA_SUBJECT, "Hey! ");


            email.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://"+ getPackageName() + "/" + R.drawable.ic_launcher));
startActivity(Intent.createChooser(email, "Sending........"));

Please suggest me what is worng in this code thanks.

Upvotes: 1

Views: 2519

Answers (1)

Givi
Givi

Reputation: 3283

You can only attach an image to mail if the image is located in the SDCARD. So, you'll need to copy the image to SD and then attach it.

InputStream in = null;
OutputStream out = null;
try
{
in = getResources().openRawResource(R.raw.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);
        }
    }


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..."));

Upvotes: 1

Related Questions