0

I am using the following code to send emails in my app

Sending Email in Android using JavaMail API without using the default/built-in app

This has worked before but now has stopped with a NetworkOnMainThreadExceoption. I know the solution is to use a AsyncTask but I do not know how to convert the class I have now to work with AsyncTask. Not used them before.

Below is the Send part of the class that is failing

public class EmailProvider extends Authenticator { 
    private static String emailUsername  = ""; 
    private static String emailPassword = "";
    private static String emailFrom  = ""; 
    private static String emailDefaultSMTPport = 
    private static String emailDefaultSocketFactoryPort = 
    private static String emailHost = ""; 

    private boolean emailAuth; 
    private boolean emailDebuggable; 

    private Multipart emailMultipart; 

    public EmailProvider(Context context) { 
        //this.context = context;

        emailDebuggable = false; // debug mode on or off - default off 
        emailAuth = true; // smtp authentication - default on 

        emailMultipart = new MimeMultipart(); 

    } 

    public boolean send(String emailAddress, String pEmailSubject, String pEmailBody) throws Exception { 

        Properties props = setProperties(); 

        Session session = Session.getInstance(props, this); 

        MimeMessage msg = new MimeMessage(session); 

        msg.setFrom(new InternetAddress(emailFrom)); 

        msg.setRecipients(MimeMessage.RecipientType.TO, emailAddress); 

        msg.setSubject(pEmailSubject); 
        msg.setSentDate(new Date()); 

        // setup message body 
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(pEmailBody);

        emailMultipart.addBodyPart(messageBodyPart); 

        // Put parts in message 
        msg.setContent(emailMultipart); 

        // send email 
        Transport.send(msg); 

        return true; 
    } 

}

Thanks for your Time

Community
  • 1
  • 1
James Dudley
  • 915
  • 4
  • 15
  • 35

1 Answers1

0

Declare this asyncTask in the activity from where you are calling send() method:

private class SendEmailTask extends AsyncTask<Object, Object, Object> {        
        @Override
        protected Object doInBackground(Object... arg0) {
            yourEmailProviderObj.send(emailAddress, pEmailSubject, pEmailBody);
            return "executed";
        }
}

And make this call instead of your send() method call:

new SendEmailTask().execute();

Thanks.

Pratik Sharma
  • 13,307
  • 5
  • 27
  • 37