我已经研究了一段时间并尝试了几种不同的属性组合并不断收到此错误。我们能够成功发送电子邮件与其他smtp服务器(和不同的属性)没有问题,但Exchange将无法正常工作。
关于此主题的其他答案提到您需要1.4.3版或更新版本的JavaMail,因为Exchange服务器需要NTLM。我正在使用JavaMail 1.4.7。其他答案说Exchange默认情况下不支持SMTP。
这是最新的代码:
// this is inside a Junit
String emailTo = "me@gmail.com";
String emailFrom = "me@mycompany.com";
String message = "testing exchange";
String host = "smtp.office365.com";
String user = "obfuscated";
String password = "obfuscated";
StringBuilder body = new StringBuilder(message);
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.from", "me@mycompany.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
props.put("mail.debug", "true");
Authenticator authenticator = new Authenticator();
props.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
Session session = Session.getInstance(props, authenticator);
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(as_email_from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(as_email_to));
message.setSubject("Testing exchange server");
message.setContent(body.toString(), "text/html");
message.setSentDate(new Date());
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, smtpSettings.getUser(), smtpSettings.getPswd());
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;
public Authenticator() {
String username = "myuser";
String password = "mypass";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
这是调试:
DEBUG: SMTPTransport connected to host "smtp.office365.com", port: 587
DEBUG SMTP SENT: EHLO Brian-PC
DEBUG SMTP RCVD: 250-BY2PR01CA020.outlook.office365.com Hello [207.250.96.62]
250-SIZE 78643200
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-AUTH
250-8BITMIME
250-BINARYMIME
250 CHUNKING
DEBUG SMTP Found extension "SIZE", arg "78643200"
DEBUG SMTP Found extension "PIPELINING", arg ""
DEBUG SMTP Found extension "DSN", arg ""
DEBUG SMTP Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP Found extension "STARTTLS", arg ""
DEBUG SMTP Found extension "AUTH", arg ""
DEBUG SMTP Found extension "8BITMIME", arg ""
DEBUG SMTP Found extension "BINARYMIME", arg ""
DEBUG SMTP Found extension "CHUNKING", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: use8bit false
DEBUG SMTP SENT: MAIL FROM:<me@mycompany.com>
DEBUG SMTP RCVD: 530 5.7.1 Client was not authenticated
答案 0 :(得分:1)
基于调试输出,我相信你实际上并没有使用JavaMail 1.4.7。检查您的CLASSPATH,服务器上的lib目录等。
答案 1 :(得分:0)
检查您的Exchange服务器是否需要启用TLS,如果需要,请通过设置此属性启用TLS
mail.smtp.starttls.enable=true
这解决了我的问题。