[英]Problem sending mail with javamail
我正在嘗試使用javamail API向自己發送電子郵件。 我已經正確地遵循了在網上找到的代碼,但是似乎無法正常工作。 我得到的錯誤是:
Exception in thread "main" javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client
這是否意味着我的計算機不支持身份驗證?
public class Emails
{
public static void main(String[] args) throws MessagingException
{
Emails e = new Emails();
e.sendMail();
}
public void sendMail() throws MessagingException
{
boolean debug = false;
String subject = "Testing";
String message = "Testing Message";
String from = "myemail@email.com";
String[] recipients = {"myemail@email.com"};
// create some properties and get the default Session
Session session = getSession();
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
private Session getSession()
{
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.host", "smtp.examplehost.com");
properties.setProperty("mail.smtp.port", "25");
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator
{
private PasswordAuthentication authentication;
public Authenticator()
{
String username = "myusername";
String password = "mypassword";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
}
}
當我從該服務器發送電子郵件時,我要做的是通過ssh登錄到服務器(login.server.com等),然后可以從郵件服務器(smtp.server.com等)發送電子郵件。 我需要在Java中模仿
解決:使用SMTPSSLTransport類
我有同樣的問題,有一次沒有在stackoverflow上找到答案。 @JPC的答案提供了一個(很小的)線索。
從javamail 1.4.3(請參閱參考資料)開始,javamail將拒絕通過未加密的通道發送純文本憑證。 因此,啟用TLS傳輸是一種解決方案。 如果服務器支持,則另一種解決方案是嘗試另一種身份驗證方法,例如NTLM或SASL。 另一個解決方案是還原為JavaMail 1.4.1,它毫無疑問地發送憑證。 這樣做的好處是您的代碼不必更改。 問題中的代碼可以正常工作。 缺點顯然是您以明文形式發送憑據,但是如果您的Exchange管理員允許,則...在我的情況下,郵件服務器不支持TLS,因此我別無選擇。
參考文獻:
確保您有一個smtp服務器(smtp.examplehost.com)可以實際發送電子郵件。 確保您的smtp服務器允許“ myemail@email.com”發送電子郵件。
這些是標准smtp服務器進行的一些安全檢查。
這可能是您敲錯了端口。 我想您正在使用IMAP協議:對於基於SSL的IMAP,您必須連接到端口993
SMTPSSLTransport解決了問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.