[java] javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

I am getting issue while sending email.

javax.mail.SendFailedException: Sending failed;
  nested exception is: 
    javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is: 
    java.net.ConnectException: Connection refused: connect
    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at org.apache.jsp.online_005fScheme_005fSend_005fMail_jsp.sendMail(online_005fScheme_005fSend_005fMail_jsp.java:116)
    at org.apache.jsp.online_005fScheme_005fSend_005fMail_jsp._jspService(online_005fScheme_005fSend_005fMail_jsp.java:416)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
    at java.lang.Thread.run(Thread.java:619)

I use below code snipet.

Properties props = new Properties();
     props.put("mail.smtp.host", "10.101.3.229");

email send program is running on tomcat 5. Some times it is working fine and some times it results above exception. once it satart resulting above exception it results the same on every access. but as soon as i restart tomcat server it starts working fine again.

So i could not find what is reason. as sometimes same is working fine and sometimes results above exception.

Can anybody help me out this issue.

This question is related to java jakarta-mail tomcat5.5

The answer is


Just look at this solution, make sure you've turned access on to less secure apps on your google account :javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25


I was also facing the same error. The reason for this is that there is no smtp server on your environment. For creating a fake smtp server I used this fake-smtp.jar file for creating a virtual server and listening to all the requests. If you are facing the same error, I recommend you to use this jar and run it after extracting and then try to run your application.

Download latest version of fake smtp


Try to set the property when starting JVM, for example, add -Djava.net.preferIPv4Stack=true.

You can't set it when code running, as the java.net just read it when jvm starting.

And about the root cause, this article give some hint: Why do I need java.net.preferIPv4Stack=true only on some windows 7 systems?.


It is very clear from your exception that it is trying to connect to localhost and not to 10.101.3.229

exception snippet : Could not connect to SMTP host: localhost, port: 25;

1.) Please check if there are any null check which is setting localhost as default value

2.) After restarting, if it is working fine, then it means that only at first-run, the proper value is been taken from Properties and from next run the value is set to default. So keep the property-object as a singleton one and use it all-over your project


package sn;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
  public static void main(String[] args) {
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
 // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = "[email protected]";//
    final String password = "0000000";
    try{
      Session session = Session.getDefaultInstance(props, 
                          new Authenticator(){
                             protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, password);
                             }});

   // -- Create a new message --
      Message msg = new MimeMessage(session);

   // -- Set the FROM and TO fields --
      msg.setFrom(new InternetAddress("[email protected]"));
      msg.setRecipients(Message.RecipientType.TO, 
                        InternetAddress.parse("[email protected]",false));
      msg.setSubject("Hello");
      msg.setText("How are you");
      msg.setSentDate(new Date());
      Transport.send(msg);
      System.out.println("Message sent.");
    }catch (MessagingException e){ 
      System.out.println("Erreur d'envoi, cause: " + e);
    }
  }
}

This should not happen. Can you try doing this? Use the system properties and set the property as below:

Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", "10.101.3.229");

And if you have a port associated, then set this as well.

properties.setProperty("mail.smtp.port", "8080");

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to jakarta-mail

Base64: java.lang.IllegalArgumentException: Illegal character javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25 Solve error javax.mail.AuthenticationFailedException java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail Javamail Could not convert socket to TLS GMail Send Mail to multiple Recipients in java Error - trustAnchors parameter must be non-empty javax.mail.AuthenticationFailedException: failed to connect, no password specified? package javax.mail and javax.mail.internet do not exist How do I send an HTML email?

Examples related to tomcat5.5

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25 How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream? How to change Java version used by TOMCAT? Eclipse "Server Locations" section disabled and need to change to use Tomcat installation