Thursday, 3 October 2013

How to Send Email from Jsp/Servlet.

Send a Simple Email from JSP

for that you have to add mail.jar into your web application project.

First of all you have to get following parameters from jsp to the servlet

String login=request.getParameter("your username");
String password=request.getParameter("your password");
String from = request.getParameter("from");
String to = request.getParameter("to");
String subject = request.getParameter("your subject");
String message = request.getParameter("your message");

in the above code we get necessary parameters from the jsp and set to the String.

following code is for the send email from the Java

                          Properties props = new Properties();

            props.put("mail.smtp.host", "smtp.gmail.com");
   
           Authenticator auth = new SMTPAuthenticator(login, password);

           Session session = Session.getInstance(props, auth);

           MimeMessage msg = new MimeMessage(session);
           msg.setText(message);
           msg.setSubject(subject);
           msg.setFrom(new InternetAddress(from));
           msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
           Transport.send(msg);


and finally you add following class to your servlet file


private class SMTPAuthenticator extends Authenticator {



       private PasswordAuthentication authentication;

       public SMTPAuthenticator(String login, String password) {
           authentication = new PasswordAuthentication(login, password);
       }

       protected PasswordAuthentication getPasswordAuthentication() {
           return authentication;
       }
   }

and done!!!

Regards,
Rajnikant

No comments:

Post a Comment