Send Email using JSP


In this article, you will get to know about sending email using Jsp. You need to take following details from user: ‘to’ email, ‘from’ email, ‘subject’ and ‘body’

Create a Emailcl.java class and add the following method in it:

public void SendEmail(String[] str_ToEmail, String str_Subject, String str_Message , String str_FromEmail)
    {
      try
      {
        String str_Host = "smtp.gmail.com";
        int int_Port = 465;
        String str_Password = "password";
        Properties obj_Properties = new Properties();
        obj_Properties.put("mail.smtp.host", str_Host);
        obj_Properties.put("mail.smtp.port", Integer.toString(int_Port));
        obj_Properties.put("mail.smtp.auth", "true"); 
        //obj_Properties.put("mail.smtp.starttls.enable", "true");
        obj_Properties.put("mail.smtp.user", str_FromEmail);
        obj_Properties.put("mail.smtp.password", str_Password); 
        obj_Properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
        obj_Properties.put("mail.smtp.socketFactory.fallback", "false");
        Session obj_Session = Session.getDefaultInstance(obj_Properties, null);
        obj_Session.setDebug(false);
        Message obj_Message = new MimeMessage(obj_Session);
        InternetAddress addressFrom = new InternetAddress(str_FromEmail);
        obj_Message.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[str_ToEmail.length];
        for (int iCtr = 0; iCtr < str_ToEmail.length; iCtr++)
        {
          addressTo[iCtr] = new InternetAddress(str_ToEmail[iCtr]);
        }
        obj_Message.setRecipients(Message.RecipientType .TO, addressTo);
        obj_Message.setSubject(str_Subject);
        obj_Message.setContent(str_Message, "text/html");
        Transport obj_Transport = obj_Session.getTransport("smtps");
        obj_Transport.connect(str_Host, int_Port, str_FromEmail, str_Password);
        obj_Transport.sendMessage(obj_Message, obj_Message.getAllRecipients() );
        obj_Transport.close();
        obj_Session = null;
        obj_Transport = null;
        obj_Message = null;
        obj_Properties = null;
      }
      catch(Exception ex)
      {
        ex.printStackTrace();
      }
    }

Tags: , ,

Comments & Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

*


2 + = 8

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>