使用asynctask发送电子邮件

时间:2016-04-27 18:08:17

标签: java android-asynctask javamail

问题:当没有AsyncTask运行此代码时,会出现错误,当在AsyncTask中运行时,似乎没有任何事情发生(因为没有发送电子邮件)

奇怪的是,当我通过eclipse运行相同的代码时,会发送电子邮件。我测试了bluestacks2和droid4x仿真器。

代码:

     new AsyncTask<Void, Void, Void>() {

                    protected Void doInBackground(Void... Void) {

                        String to = "toemail";


                        String from = "fromemail";
                        final String username = "username";//change accordingly
                        final String password = "password";//change accordingly


                        String host = "localhost";

                        Properties props = new Properties();
                        props.put("mail.smtp.auth", "true");
                        props.put("mail.smtp.starttls.enable", "true");
                        props.put("mail.smtp.host", host);
                        props.put("mail.smtp.port", "25");


                        Session session = Session.getInstance(props,
                                new javax.mail.Authenticator() {
                                    protected PasswordAuthentication getPasswordAuthentication() {
                                        return new PasswordAuthentication(username, password);
                                    }
                                });

                        try {

                            // Create a default MimeMessage object.
                            Message message = new MimeMessage(session);

                            // Set From: header field of the header.
                            message.setFrom(new InternetAddress(from));

                            // Set To: header field of the header.
                            message.setRecipients(Message.RecipientType.TO,
                                    InternetAddress.parse(to));

                            // Set Subject: header field
                            message.setSubject("TEST SUBJECT");

                            // Now set the actual message
                            message.setText("TEST BODY");

                            // Send message
                            Transport.send(message);


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

                        }
                        return null;
                    }
                }.execute();

0 个答案:

没有答案
相关问题