First of all we need to add activation.jar and mail.jar then write this code in Servlet it works fine change the mail addresses..
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
@WebServlet(urlPatterns = {"/mails2"})
public class Mails extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<html>");
out.println("<head><link rel=\"icon\" href=\"./images/bank1.ico\"/>");
out.println("<title>Servlet mails</title>");
out.println("</head>");
out.println("<body>");
HttpSession ses=request.getSession(false);
String s="xxxx@xxx.com";//change mail address(to whom)
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxx@gmail.com","xxxxxx");
//change mail address and password (from whom) accordingly
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("XXXXX@gmail.com"));
//change mail address (from whom) accordingly
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(s));
message.setSubject("Mail Testing");
message.setText("Hai Testing");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
code is working thanks for post
ReplyDelete