Sunday, January 29, 2012

send image from url as email attachemnt


                try {
                    File rootSdDirectory = Environment.getExternalStorageDirectory();

                    File pictureFile = new File(rootSdDirectory, "attachment.jpg");
                    if (pictureFile.exists()) {
                        pictureFile.delete();
                    }                  
                    pictureFile.createNewFile();

                    FileOutputStream fos = new FileOutputStream(pictureFile);

                    URL url = new URL(string);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setDoOutput(true);
                    connection.connect();
                    InputStream in = connection.getInputStream();

                    byte[] buffer = new byte[1024];
                    int size = 0;
                    while ((size = in.read(buffer)) > 0) {
                        fos.write(buffer, 0, size);
                    }
                    fos.close();
                   
                   
                   
                   
                   
                   
                    Intent sendIntent = new Intent(Intent.ACTION_SEND);
                    //Mime type of the attachment (or) u can use sendIntent.setType("*/*")
                    sendIntent.setType("image/jpeg");
                    //Subject for the message or Email
                    sendIntent.putExtra(Intent.EXTRA_SUBJECT, "My Picture");
                   
                    //Full Path to the attachment
                    Uri pictureUri = Uri.fromFile(pictureFile);
                    sendIntent.putExtra(Intent.EXTRA_STREAM, pictureUri);

                    //Use a chooser to decide whether email or mms
                    startActivity(Intent.createChooser(sendIntent, "Email:"));

                } catch (Exception e) {
                    e.printStackTrace();
                  
                }