简体   繁体   中英

how to attach bitmap file to email

I have bitmap in my code and i need to send it by email as attachment.
I saved it as file and make send intent but every time i have error (file not found).
this is my code.

save file :

private void savePicture(String filename, Bitmap b, Context ctx) {
    try {
        FileOutputStream out;
        out = ctx.openFileOutput(filename, Context.MODE_APPEND);

        b.compress(Bitmap.CompressFormat.JPEG, 40, out);
        if (b.compress(Bitmap.CompressFormat.JPEG, 40, out) == true) {
            Toast.makeText(act,"file created",Toast.LENGTH_LONG).show();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(act,e.getMessage(),Toast.LENGTH_LONG).show();
    }
}

send email :

public void sendmail (String filename){
        String path = Environment.getExternalStorageDirectory().toString();
        File file = new File(path,filename+".JPEG");
        Uri pngUri = Uri.fromFile(file);
        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.setType("text/html");
        emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, pngUri);
        startActivity(Intent.createChooser(emailIntent,"send quotation"));
}

First of all doing

b.compress(Bitmap.CompressFormat.JPEG, 40, out);
    if (b.compress(Bitmap.CompressFormat.JPEG, 40, out) == true) {

you are calling twice b.compress(Bitmap.CompressFormat.JPEG, 40, out);

You should do something like boolean success = b.compress(Bitmap.CompressFormat.JPEG, 40, out); if(success){ // Your code } boolean success = b.compress(Bitmap.CompressFormat.JPEG, 40, out); if(success){ // Your code }

Said that, are you targetting Android N or higher version? If yes, you probably need to grant uri permissions

See File providers and grant permissions from official documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM