我正在尝试使用java邮件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.DualStackPlainSocketImpl.connect0(Native : Connection拒绝:连接在java.net.DualStackPlainSocketImpl.socketConnect(Unknown源代码)在java.net.AbstractPlainSocketImpl.doConnect(Unknown源)在java.net.AbstractPlainSocketImpl.connectToAddress(Unknown源)在java.net.AbstractPlainSocketImpl.connect(Unknown源)在java.net.PlainSocketImpl.connect(未知源)在java.net.SocksSocketImpl.connect(未知源)在java。com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:312) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:236) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2019) . 29
发布于 2014-05-11 08:00:55
您没有在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);发布于 2014-05-11 08:06:57
Yo需要在本地框上安装smtp服务器,或者使用一些现有的smtp服务器(如yahoo、gmail等)。您可以在internet上获取smtp设置)。您可以使用apache服务器,并了解有关它的邮件发送api。
https://stackoverflow.com/questions/23590320
复制相似问题