javax.mail does not want to send my mail from my web application but it send mail from my console appusing java mail message object between web applicationsJavaMail with Gmail: 535-5.7.1 Username and Password not acceptedEmail Client in javawhy mail content is sent as attachment when I send it to Hotmail account?smtp server to use for sending email through java mail apiSending mail from java code - the reliable wayTransport.send(message) throws Network is unreachable while trying to send the mail from my java applicationJavaMail - multiple sendersHandle exception in JavaMailSenderSending Multipart MimeMessage sends an empty email
voltage of sounds of mp3files
 
 Valid Badminton Score?
 
 If you attempt to grapple an opponent that you are hidden from, do they roll at disadvantage?
 
 Confused about a passage in Harry Potter y la piedra filosofal
 
 How was Earth single-handedly capable of creating 3 of the 4 gods of chaos?
 
 Can criminal fraud exist without damages?
 
 What will be the benefits of Brexit?
 
 Bash method for viewing beginning and end of file
 
 What is the opposite of 'gravitas'?
 
 Was Spock the First Vulcan in Starfleet?
 
 How can I use the arrow sign in my bash prompt?
 
 Coordinate position not precise
 
 Is exact Kanji stroke length important?
 
 Is the destination of a commercial flight important for the pilot?
 
 Greatest common substring
 
 Is there a problem with hiding "forgot password" until it's needed?
 
 How does it work when somebody invests in my business?
 
 What is the intuitive meaning of having a linear relationship between the logs of two variables?
 
 Everything Bob says is false. How does he get people to trust him?
 
 Will it be accepted, if there is no ''Main Character" stereotype?
 
 Understanding "audieritis" in Psalm 94
 
 Is a roofing delivery truck likely to crack my driveway slab?
 
 What's the purpose of "true" in bash "if sudo true; then"
 
 What would happen if the UK refused to take part in EU Parliamentary elections?
javax.mail does not want to send my mail from my web application but it send mail from my console app
using java mail message object between web applicationsJavaMail with Gmail: 535-5.7.1 Username and Password not acceptedEmail Client in javawhy mail content is sent as attachment when I send it to Hotmail account?smtp server to use for sending email through java mail apiSending mail from java code - the reliable wayTransport.send(message) throws Network is unreachable while trying to send the mail from my java applicationJavaMail - multiple sendersHandle exception in JavaMailSenderSending Multipart MimeMessage sends an empty email
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");
 
java javamail java-ee-7 glassfish-4
add a comment |
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");
 
java javamail java-ee-7 glassfish-4
add a comment |
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");
 
java javamail java-ee-7 glassfish-4
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");
 
java javamail java-ee-7 glassfish-4
java javamail java-ee-7 glassfish-4
edited Mar 8 at 7:42
Stu076
asked Mar 7 at 11:37
Stu076Stu076
3218
3218
add a comment |
add a comment |
 2 Answers
 2
 
active
oldest
votes
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.
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 8 at 6: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 8 at 7: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 8 at 22:40
add a comment |
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");
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 8 at 6:03
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55042869%2fjavax-mail-does-not-want-to-send-my-mail-from-my-web-application-but-it-send-mai%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
 2 Answers
 2
 
active
oldest
votes
 2 Answers
 2
 
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
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 8 at 6: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 8 at 7: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 8 at 22:40
add a comment |
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.
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 8 at 6: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 8 at 7: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 8 at 22:40
add a comment |
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.
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.
answered Mar 7 at 18:36
Bill ShannonBill Shannon
24.1k53134
24.1k53134
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 8 at 6: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 8 at 7: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 8 at 22:40
add a comment |
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 8 at 6: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 8 at 7: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 8 at 22: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 8 at 6:09
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 8 at 6: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 8 at 7:44
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 8 at 7:44
1
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 8 at 22:40
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 8 at 22:40
add a comment |
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");
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 8 at 6:03
add a comment |
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");
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 8 at 6:03
add a comment |
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");
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");
answered Mar 7 at 16:11
unwichtichunwichtich
11.8k23955
11.8k23955
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 8 at 6:03
add a comment |
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 8 at 6:03
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 8 at 6:03
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 8 at 6:03
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
 
But avoid …
- Asking for help, clarification, or responding to other answers.
 - Making statements based on opinion; back them up with references or personal experience.
 
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55042869%2fjavax-mail-does-not-want-to-send-my-mail-from-my-web-application-but-it-send-mai%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown