Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android attach image to email doesn't work

I'm trying to send email from my application with it's logo.
But I receive the email when the attachment in string format(should be png).
My code:

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

What should I do?

like image 366
NickF Avatar asked Aug 19 '13 10:08

NickF


People also ask

Why are my emails with photo attachments not sending?

Messages with photos can remain unsent because the photo file(s) add up to more data than can be sent in an email message, but you should get a warning message if that happens. This can also happen if there is not enough storage space on your device or account to hold the encoded image file.

Why is Gmail not letting me attach photos?

It's possible that one of your browser extensions is limiting the functionality of Gmail. Another reason why you can't attach files in Gmail is that your browser does not support the email service. If you want to access the best experience, opt for supported browsers like Edge, Chrome, Safari, and Firefox.


1 Answers

You cannot attach files to an email from your internal resources. You must copy it to a commonly accessible area of the storage like the SD Card first.

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

This is required as the resources you bundle with your app are read only and sandboxed to your application. The URI that the email client receives is one it cannot access.

like image 196
Raghav Sood Avatar answered Sep 27 '22 18:09

Raghav Sood