Java 通过电子邮件发送从SurfaceView摄像头单击的文本消息和图像

Java 通过电子邮件发送从SurfaceView摄像头单击的文本消息和图像,java,android,email,android-image,Java,Android,Email,Android Image,我能够成功地从应用程序传递文本消息,但无法邮寄图像。我想传递邮件以及函数中计时器活动中的图像-- 1.)主要活动 public class MainActivity extends Activity { ImageView image; Activity context; Preview preview; Camera camera; Button exitButton; ImageView fotoButton; LinearLayou

我能够成功地从应用程序传递文本消息,但无法邮寄图像。我想传递邮件以及函数中计时器活动中的图像--

1.)主要活动

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

    }

}

好的,我会提供一些样品来跟进

在一个活动中,您启动了一个摄像头,目的是捕捉这样的图像

 Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST); 
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"));
在同一活动的onActivityResult中,您将设置缩略图并将其写入外部存储器

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

    }  
要在电子邮件中附加图像,您可以写以下内容

 Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST); 
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"));

希望这将帮助您完成任务。

尝试我使用的代码。

 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);
    }
附件代码

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

尝试图像数据url。它类似于普通文本,您可以将其放入

您的化身的数据url为:

数据:图像/png;base64,2.这个词的意思是:一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域,一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域的一个研究领域,一个研究领域,一个关于一个研究领域的J95G4VAO+qUsgJGwC++SKp4.F/D/D/D/D/D/D/D/D/D/D/3三级社区社区社区(10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 33WLEAOTHQQBIOZD4JTOANbyEJ/w9fnNBOzkTAOszxmBP+5+SNK2TWNWAAAAAAAELFTKSUQMCC

你为什么要放弃整个项目?仅在问题或模式出错的地方放置一些特定部分。@ShreeKrishna hi…实际上我想在Main活动中发送从surfaceview摄像头单击的图像,我可以将文本发送到邮件中,但尽管有各种效果,我无法发送正在单击并保存在路径字符串path=“/sdcard/images/"; 动态地…首先存储图像,而不仅仅是您可以将其附加到邮件上,否则附件只是blank@AjayPandya图像已成功存储在文件夹中,但我无法将动态单击的图像发送到邮件对不起,我有午餐时间。请查看此链接它帮助您我在后台发送邮件,而不使用谷歌的gmail应用程序。所有邮件和图像都在后台传递。好的,那么邮件在未附加图像时是否成功发送?邮件发送非常成功,但我无法保持图像路径并将其发送到mailid..这是从surfaceview cameraI动态点击的我查看了你的每一行,一切都是正确的。。。尝试记录路径变量。它是否正确地指向图像?是的,每次都保存图像…如果我使用字符串path=“/sdcard/images/a.png”这样的路径;我手动将图像a.png放在该文件夹中,该文件夹用于用该图像填充我的邮件,但我想要我单击并保存在文件夹“/sdcard/images/”中的图像;请你指出我应该在哪里修改我上面的代码,我很抱歉回复晚了,我正忙于一些工作,所以。让我看看你的代码,请给我一些时间。shreya是的,请注意,我超出了时间限制,感到紧张:(shreya,请查看此链接:所以你只想拍摄图像并发送到电子邮件?