【问题标题】:JavaMail - Unable to send mail using SSLJavaMail - 无法使用 SSL 发送邮件
【发布时间】:2015-08-25 18:36:25
【问题描述】:

我正在尝试通过使用以 office365 作为主机的 JavaMail 启用 SSL 来发送邮件。当我将主机用作smtp.gmail.com 时,它工作正常但不适用于smtp.office365.com 以下是我的方法:

public class SendMail
{

     public static void main(String args[]){
        String username = "abc@xyz.com";
        String password = "abc123";
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.office365.com");
        properties.put("mail.smtp.socketFactory.port",995);
        properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");

        Session session = null;

        if (authenticationRequired) {
          session = Session.getInstance(properties,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(userName,password);
                }
              });
        }else{
             session = Session.getDefaultInstance(properties);  
       }
       try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setSubject("Test mail");
            message.setContent("Test Mail", "text/html");
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(john@gmail.com));

            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.sendMessage(message,message.getAllRecipients());
       }catch(Exception e){
          e.printStack();
       }
     }
  }

它抛出异常为 - Could not connect to SMTP host: smtp.office365.com, port: 995 response: -1。我也尝试将端口设置为993,但这也不起作用。请帮帮我。 Other approaches are also welcome

【问题讨论】:

  • 我没有回答你的问题,但我使用这个库https://commons.apache.org/proper/commons-email/ 发送邮件......并且运行良好。试试吧!构建在 Java Mail API 之上。
  • 如果你用-Djavax.net.debug=ssl启动你的程序,输出是什么?

标签: java email ssl jakarta-mail


【解决方案1】:

如您所说,使用 gmail 是否将 gmail 的证书导入您的密钥库?

【讨论】:

  • 尝试添加这个:props.put("mail.smtp.ssl.trust", "smtpserver");
  • 我也试过了,但得到同样的错误....我没有导入证书
  • 尝试使用端口 587 或看看这个帖子:stackoverflow.com/questions/6244694/…
  • 我也尝试过使用端口 587,但我得到了像 - Failed to connect host: office365 and Port 25 这样的错误,尽管我们正在使用端口 587
猜你喜欢
  • 2016-04-12
  • 2014-09-13
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 2019-08-10
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多