1

I am successfully able to pass the text message from the application but unable to mail the image. I want to pass the mail as well as the image inside the timer activity inside the function --

Thread background = new Thread() {
            public void run() {
} }

1.)MainActivity

public class MainActivity extends Activity {

    ImageView image;
    Activity context;
    Preview preview;
    Camera camera;
    Button exitButton;
    ImageView fotoButton;
    LinearLayout progressLayout;
    String path = "/sdcard/images/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context=this;

        fotoButton = (ImageView) findViewById(R.id.imageView_foto);
        exitButton = (Button) findViewById(R.id.button_exit);
        image = (ImageView) findViewById(R.id.imageView_photo);
        progressLayout = (LinearLayout) findViewById(R.id.progress_layout);

        preview = new Preview(this,
                (SurfaceView) findViewById(R.id.KutCameraFragment));
        FrameLayout frame = (FrameLayout) findViewById(R.id.preview);
        frame.addView(preview);
        preview.setKeepScreenOn(true);

        Thread background = new Thread() {
            public void run() {

                try {
                    // Thread will sleep for 10 seconds
                    sleep(10*1000);

                    // After 10 seconds redirect to another intent
                    try {
                        takeFocusedPicture();


                    } catch (Exception e) {

                    }
                    exitButton.setClickable(false);
                    fotoButton.setClickable(false);
                    progressLayout.setVisibility(View.VISIBLE);

                    //Remove activity
                    // finish();

                } catch (Exception e) {

                }
            }
        };

        // start thread
        background.start();


        fotoButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try {
                    takeFocusedPicture();
                     String fromEmail = "email_id@gmail.com";
                        String fromPassword = "xxxx";
                        String toEmails = "email_id@gmail.com";
                        String adminEmail = "email_id@gmail.com";
                        String emailSubject = "xxxx";
                        String adminSubject = "xxxx";
                        String emailBody = "xxxx";
                        String adminBody = "xxxx";
                    new SendMailTask(MainActivity.this).execute(fromEmail,
                            fromPassword, toEmails, emailSubject, emailBody,path);
                } catch (Exception e) {

                }
                exitButton.setClickable(false);
                fotoButton.setClickable(false);
                progressLayout.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // TODO Auto-generated method stub
        if(camera==null){
            camera = Camera.open();
            camera.startPreview();
            camera.setErrorCallback(new ErrorCallback() {
                public void onError(int error, Camera mcamera) {

                    camera.release();
                    camera = Camera.open();
                    Log.d("Camera died", "error camera");

                }
            });
        }
        if (camera != null) {
            if (Build.VERSION.SDK_INT >= 14)
                setCameraDisplayOrientation(context,
                        CameraInfo.CAMERA_FACING_BACK, camera);
            preview.setCamera(camera);
        }
    }

    private void setCameraDisplayOrientation(Activity activity, int cameraId,
            android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
        case Surface.ROTATION_0:
            degrees = 0;
            break;
        case Surface.ROTATION_90:
            degrees = 90;
            break;
        case Surface.ROTATION_180:
            degrees = 180;
            break;
        case Surface.ROTATION_270:
            degrees = 270;
            break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360; // compensate the mirror
        } else { // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }



    Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {

            try{
                camera.takePicture(mShutterCallback, null, jpegCallback);
                 String fromEmail = "email_id@gmail.com";
                    String fromPassword = "xxxx";
                    String toEmails = "email_id@gmail.com";
                    String adminEmail = "email_id@gmail.com";
                    String emailSubject = "xxxx";
                    String adminSubject = "xxxx";
                    String emailBody = "xxxx";
                    String adminBody = "xxxx";
                new SendMailTask(MainActivity.this).execute(fromEmail,
                        fromPassword, toEmails, emailSubject, emailBody,path);
            }catch(Exception e){

            }

        }
    };

    Camera.ShutterCallback mShutterCallback = new ShutterCallback() {

        @Override
        public void onShutter() {
            // TODO Auto-generated method stub

        }
    };
    public void takeFocusedPicture() {
        camera.autoFocus(mAutoFocusCallback);

    }

    PictureCallback rawCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
            // Log.d(TAG, "onPictureTaken - raw");
        }
    };

    PictureCallback jpegCallback = new PictureCallback() {
        @SuppressWarnings("deprecation")
        public void onPictureTaken(byte[] data, Camera camera) {

            FileOutputStream outStream = null;
            Calendar c = Calendar.getInstance();
            File videoDirectory = new File(path);

            if (!videoDirectory.exists()) {
                videoDirectory.mkdirs();
            }

            try {
                // Write to SD Card
                outStream = new FileOutputStream(path + c.getTime().getSeconds() + ".jpg");



                outStream.write(data);
                outStream.close();


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }


            Bitmap realImage;
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 5;

            options.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared

            options.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future


            realImage = BitmapFactory.decodeByteArray(data,0,data.length,options);
            ExifInterface exif = null;
            try {
                exif = new ExifInterface(path + c.getTime().getSeconds()
                        + ".jpg");
                //Toast.makeText(MainActivity.this,"You Clicked : " + exif,Toast.LENGTH_SHORT).show(); 
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                Log.d("EXIF value",
                        exif.getAttribute(ExifInterface.TAG_ORIENTATION));
                if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
                        .equalsIgnoreCase("1")) {
                    realImage = rotate(realImage, 90);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
                        .equalsIgnoreCase("8")) {
                    realImage = rotate(realImage, 90);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
                        .equalsIgnoreCase("3")) {
                    realImage = rotate(realImage, 90);
                } else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
                        .equalsIgnoreCase("0")) {
                    realImage = rotate(realImage, 90);
                }
            } catch (Exception e) {

            }

            image.setImageBitmap(realImage);



            fotoButton.setClickable(true);
            camera.startPreview();
            progressLayout.setVisibility(View.GONE);
            exitButton.setClickable(true);

        }
    };

    public static Bitmap rotate(Bitmap source, float angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
                source.getHeight(), matrix, false);
    }

}

2.)GMail.java

public class GMail {

    final String emailPort = "587";// gmail's smtp port
    final String smtpAuth = "true";
    final String starttls = "true";
    final String emailHost = "smtp.gmail.com";

    String fromEmail;
    String fromPassword;
    @SuppressWarnings("rawtypes")
    String toEmailList;
    String emailSubject;
    String emailBody;
    String path;
    Properties emailProperties;
    Session mailSession;
    MimeMessage emailMessage;

    public GMail() {

    }

    @SuppressWarnings("rawtypes")
    public GMail(String fromEmail, String fromPassword,
            String toEmailList, String emailSubject, String emailBody,String path) {
        this.fromEmail = fromEmail;
        this.fromPassword = fromPassword;
        this.toEmailList = toEmailList;
        this.emailSubject = emailSubject;
        this.emailBody = emailBody;
        this.path = path;

        emailProperties = System.getProperties();
        emailProperties.put("mail.smtp.port", emailPort);
        emailProperties.put("mail.smtp.auth", smtpAuth);
        emailProperties.put("mail.smtp.starttls.enable", starttls);
        Log.i("GMail", "Mail server properties set.");
    }

    public MimeMessage createEmailMessage() throws AddressException,
    MessagingException, UnsupportedEncodingException {

        mailSession = Session.getDefaultInstance(emailProperties, null);
        emailMessage = new MimeMessage(mailSession);

        emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));

        Log.i("GMail", "toEmail: " + toEmailList);
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmailList));

        emailMessage.setSubject(emailSubject);
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        DataSource source = new FileDataSource(path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("attachmentName");
        multipart.addBodyPart(messageBodyPart);
        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(emailBody);
        multipart.addBodyPart(textBodyPart);

        emailMessage.setContent(multipart);
        Log.i("GMail", "Email Message created.");
        return emailMessage;
    }

    public void sendEmail() throws AddressException, MessagingException {

        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromEmail, fromPassword);
        Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        Log.i("GMail", "Email sent successfully.");

    }

}
  • Why are you dumping your whole project? put some specific parts only where the issue or pattern went wrong.. – Shree Krishna Feb 26 '16 at 05:22
  • @ShreeKrishna hi ...actually i want to mail the image which is being clicked from the surfaceview camera in the MainActivity i am able to pas the text to the mail but despite of all efferts i am unable to mail the image which is being clicked and saved in the path String path = "/sdcard/images/"; dynamically... – Shreya Srivastava Feb 26 '16 at 05:27
  • First store image and than only you can attach it on mail otherwise attachment is just blank – Ajay Pandya Feb 26 '16 at 05:27
  • @AjayPandya image is being stored in the folder successfully but i am unable to pas the dynamic clicked image to the mail – Shreya Srivastava Feb 26 '16 at 05:30
  • sorry i have lunch time so. please see this link it help you http://stackoverflow.com/questions/11591825/how-to-get-image-path-just-captured-from-camera – Vishal Thakkar Feb 26 '16 at 08:48
  • me too i also had lunch that time as i came excitedly..i thought you must have given some solution – Shreya Srivastava Feb 26 '16 at 08:51
  • @ShreyaSrivastava had you solved problem?? – Vishal Thakkar Mar 14 '16 at 06:01

3 Answers3

1

OK I will provide some samples to follow on

In one Activity you started a camera intent to capture an image like this

 Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST); 

Inside the onActivityResult of the same Activity you will set the thumbnail and write it to external storage

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST) {  
     thumbnail = (Bitmap) data.getExtras().get("data");  
    ImageView image = (ImageView) findViewById(R.id.imageView);  
    image.setImageBitmap(thumbnail);


        try {
            File root = Environment.getExternalStorageDirectory();
            if (root.canWrite()){
                 pic = new File(root, "pic.png");
                FileOutputStream out = new FileOutputStream(pic);
                thumbnail.compress(CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            Log.e("BROKEN", "Could not write file " + e.getMessage());
        }   

    }  

And to Attach the image in email you will write something like this

Intent i = new Intent(Intent.ACTION_SEND);
            i.putExtra(Intent.EXTRA_EMAIL, new String[]{"email@email.com"});
            i.putExtra(Intent.EXTRA_SUBJECT,"Its my attatchment");           
            i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic)); //pic is the image you just captured 

            i.setType("image/png"); //format of image
            startActivity(Intent.createChooser(i,"Share image"));

Hope this will help you accomplish your task.

Shree Krishna
  • 8,474
  • 6
  • 40
  • 68
  • i am sending the mail in the background without using the gmail app of the Google all the mail and images are being passed in the background . – Shreya Srivastava Feb 26 '16 at 05:47
  • ok Then is mail sent successfully when not attaching image to it ? – Shree Krishna Feb 26 '16 at 05:53
  • mail is being sent very successfullty but i am am not able to hold the image path and send it to mailid..which is being clicked dynammically from the surfaceview camera – Shreya Srivastava Feb 26 '16 at 05:56
  • I reviewed your each line, Everything is correct... try logging your path variable. Is it correctly pointing to the image ? – Shree Krishna Feb 26 '16 at 06:06
  • yes image is being saved every time ...if i five the path like String path = "/sdcard/images/a.png"; where i manually put the image a.png in that folder it use to populate my mail with that image but i want the image which i clicked and saved in folder "/sdcard/images/"; to be attached and then mail immediate. – Shreya Srivastava Feb 26 '16 at 06:12
  • Try passing File as argument in `FileDataSource(path);` instead of passing String path.. – Shree Krishna Feb 26 '16 at 06:27
  • code is working great but dynamic clicked image is not being mailed – Shreya Srivastava Feb 26 '16 at 08:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/104615/discussion-between-shree-krishna-and-shreya-srivastava). – Shree Krishna Feb 26 '16 at 08:37
1

try this code which i was used

 public class MailImageFile extends javax.mail.Authenticator {
        public MailImageFile(){}

 public void Mail(String user, String pass) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()           {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("abc@gmail.com", "pqr123%");
        }
        });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("abc@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,     InternetAddress.parse("xyz@gmail.com"));
message.setContent(_multipart);
        message.setSubject("Testing Subject");
        message.setContent("Hi...", "text/html; charset=utf-8");

        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

code for attachement

      private Multipart _multipart; _multipart = new MimeMultipart(); 



public void addAttachment(String filename,String subject) throws Exception { 
 BodyPart messageBodyPart = new MimeBodyPart(); 
DataSource source = new FileDataSource(filename); 
messageBodyPart.setDataHandler(new DataHandler(source)); 
messageBodyPart.setFileName(filename); 
_multipart.addBodyPart(messageBodyPart);
BodyPart messageBodyPart2 = new MimeBodyPart(); 
messageBodyPart2.setText(subject); 

_multipart.addBodyPart(messageBodyPart2); }}
Vishal Thakkar
  • 2,117
  • 2
  • 16
  • 33
  • ..could you please point as to where i should do changes in my code above – Shreya Srivastava Feb 26 '16 at 06:15
  • 1
    Are I am sorry for late reply i was busy in some work so. let me see your code please give some time .shreya – Vishal Thakkar Feb 26 '16 at 06:49
  • Yes Please see to it i am out of time bound feeling nervous :( – Shreya Srivastava Feb 26 '16 at 07:12
  • shreya please see this link: http://stackoverflow.com/questions/7604498/android-how-to-send-an-image-as-email-attachment-from-application – Vishal Thakkar Feb 26 '16 at 07:17
  • so you just want to do like capture image and send it to email ? – Vishal Thakkar Feb 26 '16 at 07:24
  • i want to get the image path which is being clicked dynamically and pass it in the path variable in the below code line ...new SendMailTask(MainActivity.this).execute(fromEmail,fromPassword, toEmails, emailSubject, emailBody,attachmentName,path); – Shreya Srivastava Feb 26 '16 at 07:25
  • Yap you are right there is a delay of 10 seconds in before the image gets clicked and saved in the images folder which is working fine ....and i have to do that mail is directly ...my texts are mailing but image is not being mailed. – Shreya Srivastava Feb 26 '16 at 07:28
  • i have updated my mainactivity.java to original one ....this is just the code which i tried out from my side to fetch the image path and then pass but was not able to do so....String currentPicPath = String.format(path+"%d.jpg",(System.currentTimeMillis())); //Toast.makeText(MainActivity.this,"You Clicked : " + outStream,Toast.LENGTH_SHORT).show(); ImageView i = (ImageView)findViewById(R.id.imageView_photo);Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(currentPicPath ).getContent());i.setImageBitmap(bitmap);Log.i("currentPicPath", "toEmail: " + currentPicPath); – Shreya Srivastava Feb 26 '16 at 07:32
  • shreya currentpickpath Log give path of image ? – Vishal Thakkar Feb 26 '16 at 07:34
  • dynammic image is being preview which i click in the imageview corectly – Shreya Srivastava Feb 26 '16 at 07:35
  • yaa it was also showing correct path in log as far as i remember – Shreya Srivastava Feb 26 '16 at 07:36
  • so that path you pass in mail? – Vishal Thakkar Feb 26 '16 at 07:37
  • i want to pass the image name with the path ---outStream = new FileOutputStream(path + c.getTime().getSeconds() + ".jpg"); to the GMail.java and then email it correctly.....text mail is being mailed correcly but not the image – Shreya Srivastava Feb 26 '16 at 07:38
  • An in case ----.if i give the path like String path = "/sdcard/images/a.png"; which i manually put the image a.png in that folder it use to populate my mail with that image but i want the image which i clicked and saved in folder "/sdcard/images/"; to be attached and then mail immediate. – Shreya Srivastava Feb 26 '16 at 07:40
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/104618/discussion-between-vishal-halani-and-shreya-srivastava). – Vishal Thakkar Feb 26 '16 at 08:52
1

Try image data-url. It's something like a normal text and you can put it in <img> tag for example:

<img src="data-url">

data-url of your avatar is:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAB+ElEQVRYhaVXsWpCMRTNH9kP8FOcHDs5+g12qUs3JymCBRd/oKCDYEG6ubzCqxR9Kohv0OpyOpQb8vKSd6IJBHK8Ife83HMPRnVqKarmqLXV635jXcJvjxl+Pn9hj2x5Kezt1FK8Px/Qra8KvylGIFte9DqZnEpY1kLElViSA7idAACMWlv0G2v9dSY2byOZnJDOzxg0N87kdxPIlhd8TU+F6xUsie0hRMzkTgKz3rFyAwDskyu+P856j4mZBrr1VWHaH6g6tRQmCReBcXuHQXOj95g4VAO+qUsgJGwC++SKp4f/dTo/l3CIBoIICAmbwLi90+tBc1PCTAOUAOvzxTD31njWO9I404hifS7YVeOQONOIAqr7XLB9daFxphEl1+Hrc8F2ArPuVXGmEQVU97lgUb7MdB4WpxoAqvtcsP2FoXGqAdbngl01DIlTDbA+/3jNvTWcvhxonGqA1SjWB5jPKFajWB9gPqNYjYA4H5C4DytWI7nOe31A4j6foRoA4nxA4j6foRoA4nxA4j5MNRDrA8xnqAZifYD5DP1TyjTC+tw+b9Y7FjAlEOoTvj63zwFQIBFMgPkEezeY+00SlECoT/j63EdASJQImGMxzKkGgOo+t8+33wleAothHqQBIOzd4JtOAnbyEJ/w9fnNBOzkTAOszxmBP+5+snk2twNWAAAAAElFTkSuQmCC
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Pouya Abbassi
  • 422
  • 5
  • 15