我正在尝试使用java mail api并在我的servlet中使用以下代码来发送邮件。我找不到解决错误的方法。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// Recipient's email ID needs to be mentioned.
String to = "xyz@gmail.com";
// Sender's email ID needs to be mentioned
String from = "abc.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
String subject=request.getParameter("subject");
String content=request.getParameter("mail");
message.setSubject(subject);
// Now set the actual message
message.setText(content);
// Send message
Transport.send(message);
String title = "Send Email";
String res = "Sent message successfully....";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<p align=\"center\">" + res + "</p>\n" +
"</body></html>");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
我在控制台中收到以下错误:
引起:java.net.ConnectException:连接被拒绝:连接在 java.net.DualStackPlainSocketImpl.connect0(Native Method)at java.net.DualStackPlainSocketImpl.socketConnect(未知来源)at java.net.AbstractPlainSocketImpl.doConnect(未知来源)at java.net.AbstractPlainSocketImpl.connectToAddress(未知来源)at java.net.AbstractPlainSocketImpl.connect(未知来源)at java.net.PlainSocketImpl.connect(未知来源)at java.net.SocksSocketImpl.connect(未知来源)at java.net.Socket.connect(未知来源)at java.net.Socket.connect(未知来源)at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:312) 在com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:236) 在 com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2019) ... 29更多
答案 0 :(得分:2)
您没有在localhost
上运行SMTP服务器,并且您告诉API使用localhost
作为您的邮件服务器。
您需要安装本地SMTP服务器,或将smtp主机名设置为您有权访问的服务器,例如:
String host = "smtp.yourisp.com"; // real server name required here
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
答案 1 :(得分:1)
哟需要在本地机器上安装smtp服务器或使用一些现有的smtp服务器(如雅虎,gmail等。你可以在互联网上获得smtp设置)。您可以使用apache james服务器并知道发送api的邮件。