Search code examples
javaemailsmtpjakarta-mail

javax.mail: not picking up properties


I'm trying to send an email message from the code to the smtp server which is not on localhost neither on default port 25.

I have a code which looks like:

// Set the host SMTP address
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", hostname);
props.put("mail.smtp.port", "8025");
props.put("mail.smtp.auth", "true");

// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
};
Session session = Session.getInstance(props, auth);

Transport trans = session.getTransport("smtp");

...piece of the code where message is created...

trans.send(message);

but it fails on Transport.send() with a timeout -1 error as is trying to connect to the localhost on port 25 but not to the host with the port specified above.

My question is how can I check existing properties (default localhost:25) or if there is any other Transport session already spawned?


Solution

  • The send method is static so it is using the session properties of the given message. If you want to use the Transport you created you need to call connect, sendMessage, then close.

    // Set the host SMTP address
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", hostname);
    props.put("mail.smtp.port", "8025");
    props.put("mail.smtp.auth", "true");
    
    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    };
    Session session = Session.getInstance(props, auth);
    
    Transport trans = session.getTransport("smtp");
    
    //...piece of the code where message is created...
    
    trans.connect();
    try {
       trans.sendMessage(message, message.getAllRecipients());
    } finally {
       trans.close();
    }