Android-Java sending mail through Javax.mail failed

I hope everything is going fine. I was trying to send mail from android but getting an exception which I was unable to solve. I’m using https://code.google.com/archive/p/javamail-android/downloads.

MainClass:

 try {
            GMailSender sender = new GMailSender(email, password);
            sender.sendMail("Forget Password",
                    "Hello this is your code 9986",
                    sender,
                    recvicer);
        } catch (Exception e) {
            Log.e("SendMail", e.getMessage(), e);
        }

GMailSender

public class GMailSender extends javax.mail.Authenticator {
    static {
        Security.addProvider(new JSSEProvider());
    }

    final String emailHost = "smtp.gmail.com";
    private final String user;
    private final String password;
    private final Session session;

    public GMailSender(String user, String password) {
        this.user = user;
        this.password = password;
        Properties props = new Properties();
        props.setProperty("mail.smtp.ssl.enable", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.put("mail.smtp.user", user);
        props.setProperty("mail.smtp.ssl.trust", emailHost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");
        session = Session.getInstance(props, this);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body, String sender, String recipients) {
        try {
            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
            message.setSender(new InternetAddress(sender));
            message.setSubject(subject);
            message.setDataHandler(handler);
            if (recipients.indexOf(',') > 0)
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
            else
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
            Transport transport = session.getTransport("smtp");
            transport.connect(emailHost, user, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            Log.e("SendMail", e.getMessage(), e);
        }
    }


    public static class ByteArrayDataSource implements DataSource {
        private final byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

//        public ByteArrayDataSource(byte[] data) {
//            super();
//            this.data = data;
//        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream() {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }
}

Exception:

E/SendMail: Could not connect to SMTP host: smtp.gmail.com, port: 465 javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; nested exception is: java.io.IOException: Couldn’t connect using “javax.net.ssl.SSLSocketFactory” socket factory to host, port: smtp.gmail.com, 465; Exception: android.os.NetworkOnMainThreadException at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412) at javax.mail.Service.connect(Service.java:288) at javax.mail.Service.connect(Service.java:169) at com.xtenxion.letsplayqna.mail.GMailSender.sendMail(GMailSender.java:66) at com.xtenxion.letsplayqna.activities.ForgetPasswordActivity.onCreate(ForgetPasswordActivity.java:34) at android.app.Activity.performCreate(Activity.java:6975) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) Caused by: java.io.IOException: Couldn’t connect using “javax.net.ssl.SSLSocketFactory” socket factory to host, port: smtp.gmail.com, 465; Exception: android.os.NetworkOnMainThreadException at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:178) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)  at javax.mail.Service.connect(Service.java:288)  at javax.mail.Service.connect(Service.java:169)  at com.xtenxion.letsplayqna.mail.GMailSender.sendMail(GMailSender.java:66)  at com.xtenxion.letsplayqna.activities.ForgetPasswordActivity.onCreate(ForgetPasswordActivity.java:34)  at android.app.Activity.performCreate(Activity.java:6975)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6541)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)  Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448) at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102) at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90) at java.net.InetAddress.getByName(InetAddress.java:743) at java.net.InetSocketAddress.(InetSocketAddress.java:231) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:163) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)  at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)  at javax.mail.Service.connect(Service.java:288)  at javax.mail.Service.connect(Service.java:169)  at com.xtenxion.letsplayqna.mail.GMailSender.sendMail(GMailSender.java:66)  at com.xtenxion.letsplayqna.activities.ForgetPasswordActivity.onCreate(ForgetPasswordActivity.java:34)  at android.app.Activity.performCreate(Activity.java:6975)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6541)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Answer

Place your mainclass code in AsyncTask. As GMailSender cannot work on Main Thread.

  AsyncTask.execute(() -> {
                try {
                    GMailSender sender = new GMailSender(email, password);
                sender.sendMail("Forget Password",
                        "Hello this is your code 9986",
                        sender,
                        recvicer);
                } catch (Exception e) {
                    Log.e("SendMail", e.getMessage(), e);
                }
            });

Leave a Reply

Your email address will not be published. Required fields are marked *