【发布时间】:2014-07-26 13:20:32
【问题描述】:
使用 servlet(在 eclispe 中)发送邮件时出现错误。我的类路径中还包含 mail.jar 和 activation.jar。
我的 servlet 代码如下所示
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;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Controller extends HttpServlet
{
private static final long serialVersionUID = 1L;
public Controller() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
doProcess(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
doProcess(request,response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
final String user = request.getParameter("email");
final String pwd = request.getParameter("pwd");
String sub = request.getParameter("subject");
String body = request.getParameter("msg");
String to = "shiladitya1093@gmail.com";
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host","localhost");
props.put("mail.smtp.auth","true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,pwd);
}
});
//Compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(sub);
message.setText(body);
//Send message
Transport.send(message);
}catch(MessagingException e){
throw new RuntimeException(e);
}
request.setAttribute("sendMsg","Message successfully send.");
RequestDispatcher rd = request.getRequestDispatcher("contactus.jsp");
rd.forward(request, response);
}
}
错误看起来像:
HTTP 状态 500 - javax.mail.AuthenticationFailedException: 535 未定义 SMTP 服务器。在您的帐户中使用真实的服务器地址而不是 127.0.0.1。
【问题讨论】:
-
在您的帐户中使用真实的服务器地址而不是 127.0.0.1。(仔细阅读您的错误?
-
邮件服务器需要正确配置。你的smtp主机为localhost,它应该是smtp服务器的ip。如果你没有smtp服务器,使用google提供的默认smtp配置,你可以测试邮件api。
-
如何在 eclispe 中设置 smtp 服务器?
标签: java email servlets jakarta-mail