javax.mail: 不拾取属性

javax.mail: not picking up properties

我正在尝试从代码向 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)或者是否已经生成任何其他传输会话?

send 方法是静态的,因此它使用给定消息的会话属性。如果你想使用你创建的传输,你需要调用 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();
}