Home » Android » Send email with bitmap object as an attachment in Android?

Send email with bitmap object as an attachment in Android?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I want to send the bitmap as an attachment in the mail. The image is not stored in SDCARD or anywhere in the device. The bitmap object gets created at runtime and that should be sent as an attachment.

How to&Answers:

Then, you must save the Bitmap to the SDCard, and then attach it to the email (I guess, you know how to do so).

Why is it necessary to save it to the SDCard? That’s because the email app will have to read the file that it’s going to be attached; thus, you have to pass the path and filename to the email client. As any other app, the email client can only access files stored in its own private directory or the SDCard.

Answer:

/* Return Drawable Object from Specified imageUrl In Web

 @imageUrl : image Url in Web

 */

try {
/// Getting image from Web
    InputStream is = (InputStream) new URL(imageUrl).getContent();
    // storing image from stream
    drawable = Drawable.createFromStream(is, "srcName");
    is.close();
    // converting drawable object to Bitmap to store in content providers of Media
    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
    // Store image in Devise database to send image to mail
    String path = Images.Media.insertImage(getContentResolver(), bitmap,"title", null);
    Uri screenshotUri = Uri.parse(path);
    final Intent emailIntent1 = new Intent(     android.content.Intent.ACTION_SEND);
    emailIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent1.putExtra(Intent.EXTRA_STREAM, screenshotUri);
    emailIntent1.setType("image/png");
    startActivity(Intent.createChooser(emailIntent1, "Send email using"));

}
catch(Exception e) { }