I am trying to work on java mail api and have the following code in my servlet to sen mail.I cannot find out the way to resolve the error.
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 = "[email protected]";
// 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();
}
}
I am getting the following error in my console:
Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at 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 more
String from = "abc.com";
- This is not a valid email address in the first place. – Sandeep Chatterjee