【发布时间】: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