【问题标题】:javax.mail: not picking up propertiesjavax.mail:不拾取属性
【发布时间】:2019-09-26 17:12:55
【问题描述】:

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

【问题讨论】:

    标签: java email smtp jakarta-mail


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      相关资源
      最近更新 更多