Thursday, January 08, 2009

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

Properties props = new Properties();
props.setProperty("mail.host",smtpHost);
props.setProperty("mail.smtp.host", smtpHost);
Session session = Session.getDefaultInstance(props, null);


The default mail session instance is sharable across the server.

If the session is not initialized, a new session instance will be created with the properties passing in.

However, if an instance does exist, it will be returned. The passing properties will be ignored.


If there are two separate applications running in the same App server, the default session will be shared.

Be careful of your session is initialized by the other application first, and cause your passing properties become useless.

To avoid this, try use:

Session session = Session.getInstance(props, null);


or, another way, to call the smtp server explicitly:

Transport trans = session.getTransport("smtp");
trans.connect(smtpHost,-1,null,null);
trans.sendMessage(msg,msg.getAllRecipients());
trans.close();