我正在嘗試使用java
發送email
。但我面對錯誤,如下面在java/servlet中發送郵件時出錯
javax.mail.AuthenticationFailedException:連接失敗,沒有密碼指定
爲什麼會出現這個錯誤,當我還通過了身份驗證正確的電子郵件ID和密碼?
這是我的代碼
import java.io.IOException;
import java.net.PasswordAuthentication;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestMail
*/
@WebServlet("/TestMail")
public class TestMail extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestMail() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
todo(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
todo(request,response);
}
private void todo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf8");
response.setCharacterEncoding("utf8");
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.post","587");
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"[email protected]", "testing123");
}
});
Message message=new MimeMessage(session);
try {
message.setFrom(new InternetAddress("[email protected]","hello"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
message.setSubject("Testing Email");
message.setText("hello this is testing mail \n \n Congrets");
Transport.send(message);
System.out.println("Mail Sent Successfully");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
這是一個常見的錯誤,正如[JavaMail FAQ](https://javaee.github.io/javamail/FAQ#commonmistakes)中所述。 –
okk現在工作謝謝@ Bill Shannon –