1

I am trying to send mail from the Servlet. I had code like this and I am getting the Messaging Exception. There are many other similar questions in Stack Over Flow but none of them helped me. So I posted it again.

@WebServlet(name = "SendMail", urlPatterns = {"/SendMail"})
public class SendMail extends HttpServlet {
final String from = "teamwarrior20@gmail.com";
final String username = "teamwarrior20@gmail.com";
final String password = "iamfromnepal";
String to;
String subject;
String dataMessage;

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    to = req.getParameter("to");
    subject = req.getParameter("subject");
    dataMessage = req.getParameter("message");
    sendMail();
    req.getRequestDispatcher("successfullmail.jsp").forward(req, resp);
}

private void sendMail() {
    System.out.println(to);
    System.out.println(subject);
    System.out.println(dataMessage);
    Properties props = System.getProperties();

    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, password); //To change body of generated methods, choose Tools | Templates.
        }

    });
    try {
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        message.setSubject(subject);

        message.setText(dataMessage);

        Transport.send(message);

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

}

}

My stack trace is like this....

Severe:   javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.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.suraj.technepbankapplication.SendMail.sendMail(SendMail.java:74)
at com.suraj.technepbankapplication.SendMail.doPost(SendMail.java:41)
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:745)
Suraj Gautam
  • 1,524
  • 12
  • 21
  • Is there any `caused by` or `nested exception` part **after** the stacktrace you've posted? – Jozef Chocholacek Aug 31 '16 at 06:33
  • Try to change port no from 587 to 465. And Also Try adding `props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");` – Shalin Patel Aug 31 '16 at 06:49
  • I added and did what you said but it still shows the same exception. In my above code there is props.put("mail.smtp.port", "587"); but also why it is giving me exception for port number 465 – Suraj Gautam Aug 31 '16 at 06:55
  • Because you are stating smtp port but giving port number for msa SMTP port number is 465 and MSA port number is 587 that's why you may not be able to connect. [Check Here](http://stackoverflow.com/questions/15796530/what-is-the-difference-between-ports-465-and-587) – Shalin Patel Aug 31 '16 at 07:14
  • i changed it to 465 but also it's not working? – Suraj Gautam Aug 31 '16 at 07:17

3 Answers3

1

After several hours, I solved it by adding

props.put("mail.smtp.user", username);;
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "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");

I also turned the less secure apps on https://www.google.com/settings/security/lesssecureapps

Suraj Gautam
  • 1,524
  • 12
  • 21
  • You can [get rid of the socket factory properties](http://www.oracle.com/technetwork/java/javamail/faq/index.html#commonmistakes), you don't need them. You might also want to fix the other common mistakes listed in the FAQ. – Bill Shannon Aug 31 '16 at 18:56
0

Change two things in your code

Instead of writing

Properties props = System.getProperties();

change it to

Properties props = new Properties();

Also change

message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

to

message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));

This solved your issue in my computer. Give it a try and ping me.

Bishal Gautam
  • 380
  • 3
  • 16
0

I see the problem in the Properties from gmail. Could you try adding this line to properties:

props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
Angel Cuenca
  • 1,637
  • 6
  • 24
  • 46