javax.mail: не подбирая свойства - PullRequest
0 голосов
/ 09 мая 2019

Я пытаюсь отправить сообщение электронной почты с кодом на сервер smtp, который не находится на локальном хосте, ни на порту по умолчанию 25.

У меня есть код, который выглядит так:

// 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);

, но он не работает на Transport.send() с ошибкой тайм-аута -1 при попытке подключения к локальному хосту через порт 25, но не к хосту с портом, указанным выше.

Мой вопрос: как я могу проверить существующие свойства (по умолчанию localhost: 25) или если уже есть какой-то другой сеанс транспорта?

1 Ответ

2 голосов
/ 09 мая 2019

Метод send является статическим, поэтому он использует свойства сеанса данного сообщения.Если вы хотите использовать созданный вами транспорт, вам нужно позвонить connect , sendMessage , затем закрыть .

// 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();
}
...