0

I found a question on here recently that helped me get an automatic email client set up, where the app will send out an email without any user intervention to relay a forgotten password, But I'm having trouble with a NetorkOnMainThreadException. this is the method that throws the exception:

public boolean send() throws Exception {
    Properties props = _setProperties();

    if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
        Session session = Session.getInstance(props, this);
        Log.d("1", "");

        MimeMessage msg = new MimeMessage(session);
        Log.d("2", "");

        msg.setFrom(new InternetAddress(_from));
        Log.d("3", "");

        InternetAddress[] addressTo = new InternetAddress[_to.length];
        Log.d("4", "");
        for (int i = 0; i < _to.length; i++) {
            addressTo[i] = new InternetAddress(_to[i]);
            Log.d("5", "");
        }
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
        Log.d("6", "");

        msg.setSubject(_subject);
        Log.d("7", "");
        msg.setSentDate(new Date());
        Log.d("8", "");

        // setup message body
        BodyPart messageBodyPart = new MimeBodyPart();
        Log.d("9", "");
        messageBodyPart.setText(_body);
        Log.d("10", "");
        _multipart.addBodyPart(messageBodyPart);
        Log.d("11", "");

        // Put parts in message
        msg.setContent(_multipart);
        Log.d("12", "");


        // send email
        Transport.send(msg);
        Log.d("13", "");

        return true;
    } else {
        return false;
    }
}

the problem seems to occur at the "Transport.send(msg);" line since when I run the app it never logs 13.

Plays2
  • 1,115
  • 4
  • 12
  • 23

1 Answers1

0

As it says in the error, you cannot have networking on the main thread. This causes the UI to become unresponsive and blocks up all the resources until the networking task has been completed. So what you have to do is move the networking bits into an AsyncTask.

For further details refer: http://developer.android.com/reference/android/os/AsyncTask.html

shyam
  • 1,348
  • 4
  • 19
  • 37