![](/img/trans.png)
[英]WWW-Authentication / NTLM Negotiate using HttpClient with current user credentials
[英]javamail NTLM authentication using credentials of current user
如何在不指定用戶名和密碼的情況下,通過NTLM身份驗證將JavaMail API用於Exchange服務器,而是自動使用當前登錄用戶的憑據? (“單一登錄”)
我的目的是讓我的客戶端程序(在公司網絡中的Windows計算機上運行)能夠發送電子郵件,而不必指定憑據,也不必出於安全考慮而允許中繼網絡中的計算機。 (最后,我想結合使用log4j的SmtpAppender和系統屬性覆蓋來執行此操作,但是我在下面創建了SSCCE來調試問題。)
如果我指定了用戶名和與其對應的有效Windows密碼,則能夠成功使用NTLM身份驗證發送電子郵件:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailTest {
public static void main(String[] args) {
String from = "myusername@mydomain.nl";
String to = "anotherusername@mydomain.nl";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "myserver.mydomain");
props.put("mail.debug", "true");
props.put("mail.smtp.auth.mechanisms", "NTLM");
props.put("mail.smtp.auth.ntlm.domain", "mydomain");
final String username = "myusername";
final String password = "mypassword";
Session session =
Session.getInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Testing!");
message.setText("Hello world!");
Transport.send(message);
System.out.println("Sent message successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
當我使用空白密碼時,它將失敗並出現javax.mail.Authentication FailedException:535 5.7.3身份驗證失敗。
當我替換代碼以簡單地創建Session時:
Session session = Session.getInstance(props);
然后拋出以下異常,並且從調試輸出中可以看出,沒有嘗試連接到服務器:
Exception in thread "main" java.lang.RuntimeException: javax.mail.Authentication
FailedException: failed to connect, no password specified?
at MailTest.main(MailTest.java:51)
Caused by: javax.mail.AuthenticationFailedException: failed to connect, no passw
ord specified?
at javax.mail.Service.connect(Service.java:329)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
我不確定沒有用戶名和密碼是否可以執行此操作。 可能您可以編寫一些Windows特定的代碼,這些代碼可以從本地身份驗證服務中檢索用戶名和密碼,然后將其傳遞給JavaMail。 JavaMail本身當然沒有辦法做到這一點。
另外,您可能希望升級到JavaMail 1.5.2,盡管它不會幫助您解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.