0

First of all I use glassfish4 server. When I try to send an e-mail from my web test app I get an exception that usually says:

javax.mail.MessagingException: Could not connect to SMTP host: mail.host.com, port: 465, response: -1

(i also got another exception but I don't remember them), but from my SE application, it sends the e-mail correctly everytime. Also my coworker has the same code as I on his computer and the code works. I also tried to send an email with smtp.gmail.com and it works like charm, but when I try with our private server it does not work.

Here is the code from my web app:

    @WebServlet("/email")
public class Email extends HttpServlet{
    private static final String SUBJECT = "TEST";
    private static final String CONTENT = "<h1>HI</h1>"
            + "<header style='width: 100%; height=20vh; background: #ffdd1a; color: #383e72;'>"
            + "<h1>TEST</h1>"
            + "<h2>KTHXBYE</h2>"
            + "</header>";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name"),
               eMail = req.getParameter("eMail"),
               server = req.getParameter("server"),
               port = req.getParameter("port"),
               encryption = req.getParameter("encryption"),
               mailTo = req.getParameter("mailTo");
        final String username = req.getParameter("username"),
                     pass = req.getParameter("pass");
        resp.setCharacterEncoding("UTF-8");
        Session session;

        // setup acc props
        Properties props = System.getProperties();
        props.put("mail.smtp.host", server);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");

        switch (povezava) {
            case "SSL":
                props.put("mail.smtp.socketFactory.port", "port");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                break;
            case "TLS":
                props.put("mail.smtp.starttls.enable", "true");
                break;
            case "NONE":
                props.put("mail.smtp.ssl.enable", "false");
                props.put("mail.smtp.starttls.enable", "false");
                props.put("mail.smtp.ssl.trust", server);
                break;
            default:
                resp.getWriter().print("ERROR");
                return;
        }

        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, pass);
            }
        };

        // create msg
        session = Session.getDefaultInstance(props, auth);
        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        try {
            try {
                message.setFrom(new InternetAddress(eMail, name));
                message.setSubject(SUBJECT);
                MimeMultipart multipart = new MimeMultipart("related");
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setContent(CONTENT, "text/html; charset=utf-8");
                multipart.addBodyPart(bodyPart);
                message.setContent(multipart);
                // send msg
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
//                Transport transport = session.getTransport("smtp");
//                transport.connect(server, username, pass);
//                transport.sendMessage(message, message.getAllRecipients());
                Transport.send(message);
                resp.getWriter().print("Mail was send successfully");
                return;
            } catch (MessagingException ex) {
                Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
        }
        resp.getWriter().print("Sending mail failed");
    }
}

Stack trace from upper code:

javax.mail.MessagingException: Could not connect to SMTP host: mail.host.com, port: 465, response: -1
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2042)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
    at javax.mail.Service.connect(Service.java:386)
    at javax.mail.Service.connect(Service.java:245)
    at javax.mail.Service.connect(Service.java:194)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at com.zarja.testmail.Email.doPost(Email.java:113)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)

Now my SE app code:

public static void main(String[] args) {
        System.out.println(sendMyMail());
    }

    public static String sendMyMail() {
        try {
            String from = "mailaddress"; // not actual mail
            String pass = "password";
            Authenticator auth = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, pass);
                }
            };

            Session session;
            //setup account properties
            Properties props = System.getProperties();
            props.put("mail.smtp.host", "mail.host.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.getDefaultInstance(props, auth);
            session.setDebug(true);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from, "TEST"));
            message.setSubject(SUBJECT);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(CONTENT, "text/html; charset=utf-8");
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            //send message
            try {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress("host@gmail.com"));
    //                Transport transport = session.getTransport("smtp");
    //                    transport.connect("mail.host.com", from, pass);
    //                    transport.sendMessage(message, message.get

AllRecipients());
                    Transport .send(message);
                    return "SENT";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "FAILED";
        }

Thanks for the help in advance!

EDIT (how the code should actualy look):

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name"),
               eMail = req.getParameter("eMail"),
               server = req.getParameter("server"),
               port = req.getParameter("port"),
               encryption = req.getParameter("encryption"),
               mailTo = req.getParameter("mailTo");
        final String username = req.getParameter("username"),
                     pass = req.getParameter("pass");
        resp.setCharacterEncoding("UTF-8");
        Session session;

        // setup acc props
        Properties props = System.getProperties();
        props.put("mail.smtp.host", server);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "imap");

        switch (enryption) {
            case "SSL":
                props.put("mail.smtp.ssl.enable", "true");
                break;
            case "TLS":
                props.put("mail.smtp.starttls.enable", "true");
                break;
            case "NONE":
                props.put("mail.smtp.ssl.enable", "false");
                props.put("mail.smtp.starttls.enable", "false");
                props.put("mail.smtp.ssl.trust", server);
                break;
            default:
                resp.getWriter().print("ERROR");
                return;
        }

        // create msg
        session = Session.getInstance(props);
        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        try {
            try {
                message.setFrom(new InternetAddress(eMail, name));
                message.setSubject(SUBJECT);
                MimeMultipart multipart = new MimeMultipart("related");
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setContent(CONTENT, "text/html; charset=utf-8");
                multipart.addBodyPart(bodyPart);
                message.setContent(multipart);
                // send msg
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTp));
                Transport transport = session.getTransport("imap");
                transport.connect(streznikPoste, uporabniskoIme, geslo);

                Transport.send(message);
                resp.getWriter().print("Mail was send successfully");
                return;
            } catch (MessagingException ex) {
                Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
        }
        resp.getWriter().print("Sending mail failed");
    }

EDIT FIX (this seems to work):

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name"),
               eMail = req.getParameter("eMail"),
               server = req.getParameter("server"),
               port = req.getParameter("port"),
               encryption = req.getParameter("encryption"),
               mailTo = req.getParameter("mailTo");
        final String username = req.getParameter("username"),
                     pass = req.getParameter("pass");
        resp.setCharacterEncoding("UTF-8");
        Session session;

        // setup acc props
        Properties props = System.getProperties();
        props.put("mail.smtp.host", server);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.ssl.trust", server);

        switch (encryption) {
            case "SSL":
                props.put("mail.smtp.ssl.enable", "true");
                break;
            case "TLS":
                props.put("mail.smtp.starttls.enable", "true");
                break;
            case "NONE":
                props.put("mail.smtp.ssl.enable", "false");
                props.put("mail.smtp.starttls.enable", "false");
                props.put("mail.smtp.ssl.trust", server);
                break;
            default:
                resp.getWriter().print("ERROR");
                return;
        }

        // create msg
        session = Session.getInstance(props);
        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        try {
            try {
                message.setFrom(new InternetAddress(eMail, name));
                message.setSubject(SUBJECT);
                MimeMultipart multipart = new MimeMultipart("related");
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setContent(CONTENT, "text/html; charset=utf-8");
                multipart.addBodyPart(bodyPart);
                message.setContent(multipart);
                // send msg
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
                Transport transport = session.getTransport();
                transport.connect(server, username, pass);
                Transport.send(message, username, pass);
                resp.getWriter().print("Mail was send successfully");
                return;
            } catch (MessagingException ex) {
                Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
        }
        resp.getWriter().print("Sending mail failed");
    }
Stu076
  • 51
  • 1
  • 10

2 Answers2

2

A quick guess is that the problem in your code is here:

switch (povezava) {
    case "SSL":
        props.put("mail.smtp.socketFactory.port", "port");

You don't insert a port variable here...

If it's not working afterwards you could try to remove the "socketFactory" related properties, I think you don't need them.

Instead you could add:

props.put("mail.smtp.ssl.enable", "true");
unwichtich
  • 13,712
  • 4
  • 53
  • 66
  • Oops that was my mistake. The second one does not work for me because i get an error (Couldn't find the path speciefied to a valid certificate). I tried to debug that in the past by downloadning the root certificate of our server and put it into the truststore of java, but that didn't change anything. – Stu076 Mar 08 '19 at 06:03
2

First, fix all these common JavaMail mistakes.

If you can connect to one remote server but not another remote server, your configuration for that server is wrong, or you have a firewall that's preventing connection. The JavaMail FAQ has tips for debugging connection problems.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
  • Thank you Bill, I have changed that and now I get the next error: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target – Stu076 Mar 08 '19 at 06:09
  • Thank you very much Bill, I fugured it out also I posted working code in EDIT. If you have any more suggestions to make my code better I would greatly apreciate it. – Stu076 Mar 08 '19 at 07:44
  • 1
    You could merge the two try/catch blocks into one try with two catches. You're creating a Transport object but then using the static send method that ignores the Transport object (read the common mistakes again), which is then never closed. And you're creating a multipart/related message, but there's only one body part with no "related" body parts like images. You can simplify it further by getting rid of the Multipart and just setting the text/html content as the content of the MimeMessage. – Bill Shannon Mar 08 '19 at 22:40