How to Send Email in Java, Struts 2.x

This is a struts 2.x based Java “Email Sending” Web application. I have developed this project using Netbeans IDE 7.2 and Glassfish 3.1 as the Integrated Server. 

We are very much in need of this sorts of the program with the help of which can achieve various tasks so easily. Either it is validating a registration form i.e. users information by sending a unique code  through email at the time of submission of form which can help us to validate a valid existing email id and make us sure that the submitted form is ready to be saved into database table or in case we want to provide the forgot password option with our login pages in struts 2.x (JSP or Servlet or Spring-based applications). This example is very precious so make sure you go with easy and every step carefully to avoid common programming mistakes.

Download plugins or jar files for mail by clicking here (java – mail plugins ) Extract the .rar files and put them in a directory. Please do not extract .jar files.

Follow each step by going through the images carefully:
1. Click on File -> New Project

2. Select Java Web -> Web Application and Click on Next

 

3. Type the name of Project and Its location upon your taste and click Next.

4. If the server is glassfish then just click Next or you can add the server by clicking the add button.

5. In case you have clicked on add button the following window will appear. Select your type of server installed on your computer, locate its directory as per installation and click Next.

6. Now Select Struts 2 from the options in the appeared window and dis-select the create example option and finally click on Finish.

7. When everything is done and you have clicked finish. The new project will be generated by the IDE for you.

8. This might be the first look of the project(I have expanded every option).

9. Now right click on libraries as directed and click on add jar files and folders. Locate the plugins you have downloaded one by one or all by using ctrl key.

CODE:

1. index.jsp

<%--     Document   : index     Created on : Sep 18, 2012, 4:36:50 PM     Author     : Sudhanshu --%>

<%@taglib uri="/struts-tags" prefix="s" %>

<%@page contentType="text/html" pageEncoding="UTF-8"%>        

My Mailing System

2. message.jsp

<%--     Document   : message     Created on : Sep 18, 2012, 7:31:39 PM     Author     : Sudhanshu --%>
<%@taglib uri="/struts-tags" prefix="s" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
 Back
            <%     if(session.getAttribute("sms")!=null){ %>
            
            <%     }      %>

3. web.xml
struts2
org.apache.struts2.dispatcher.FilterDispatcher
struts2

4. struts.xml

 message.jsp
 index.jsp
 message.jsp
 index.jsp
        
5. SendMail.java
package email;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;

public class SendMail extends ActionSupport implements ServletRequestAware{
private String to;
private String from;
private String subject;
private String smtpServ;
private String message;
private String password1;
private String password2;
private HttpServletRequest hsr;
private HttpSession hs;
private int i;

@Override
public void setServletRequest(HttpServletRequest hsr) {
        this.hsr=hsr;
}

// Also include an inner class that is used for authentication purposes
private class SMTPAuthenticator extends Authenticator{  
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, password1);
        }
}

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to.toLowerCase();
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from.toLowerCase();
        if(!from.isEmpty()) {
            if(from.endsWith("@gmail.com")){
                this.smtpServ="smtp.gmail.com";
            }
        if(from.endsWith("@live.com")){
            this.smtpServ="smtp.live.com";
        }
        if(from.endsWith("@hotmail.com")){
            this.smtpServ="smtp.hotmail.com";
        }
        
       } 
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getPassword1() {
        return password1;
    }

    public void setPassword1(String password1) {
        this.password1 = password1;
    }

    public String getPassword2() {
        return password2;
    }

    public void setPassword2(String password2) {
        this.password2 = password2;
    }

public int sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp" );
              props.put("mail.smtp.starttls.enable","true" );
              props.put("mail.smtp.host",smtpServ);
              props.put("mail.smtp.auth", "true" );
              Authenticator auth = new SendMail.SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- Create a new message --
              Message msg = new MimeMessage(session);
              // -- Set the FROM and TO fields --
              msg.setFrom(new InternetAddress(from));
              msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
              msg.setSubject(subject);
              msg.setText(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Mr. XYZ" );
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK." );
              return 0;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return -1;
        }
  }
    @Override
    public String execute(){
    hs=hsr.getSession();
    try{
        if(hs.getAttribute("sms")!=null){
        hs.removeAttribute("sms");
        }
    }catch(Exception e){
       System.out.println("IN EXECUTE() : FIRST TRY FAILED");
    }
    try{
        i=sendMail();
        if(i==0){
            hs.setAttribute("sms", "Your E-Mail has been sent successfully to :"+to);
        }else{
            hs.setAttribute("sms", "Failed to Send Email to :"+to+" : Authentication Failed ");
        }
       return "success";
    }catch(Exception e){
        System.out.println("IN EXECUTE : SECOND TRY FAILED");
        System.out.println(e);
        hs.setAttribute("sms", "Error:::"+e);
        return "error";
    }
}
    @Override
    public void validate(){
    
        if(to.isEmpty()){
        addFieldError("to", "Email Field cannot be left blank!!!");
        }
        else if((!to.endsWith("@gmail.com"))&&(!to.endsWith("@live.com"))&&(!to.endsWith("@hotmail.com"))){
        addFieldError("from", "Email ID not valid!!!");
        }
        else if(from.isEmpty()){
        addFieldError("to", "Email Field cannot be left blank!!!");
        }
         else  if((!from.endsWith("@gmail.com"))&&(!from.endsWith("@live.com"))&&(!from.endsWith("@hotmail.com"))){
        addFieldError("from", "Email ID not valid!!!");
        }
        else if(password1.isEmpty()||password2.isEmpty())
        {
        addFieldError("password2", "Please enter your password!!!");
        }
       
        else if(!password1.equals(password2)) {
        addFieldError("password2", "Password mismatch!!!");
        }
        else if(message.isEmpty()){
        addFieldError("message", "Please Enter your message!!!");
        }
}

}

6. Back.java

package other;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;

public class Back implements ServletRequestAware {
    HttpServletRequest hsr;
    HttpSession hs;
    
    public String execute(){
        hs=hsr.getSession();
        hs.invalidate();
        return "success";
    }

    @Override
    public void setServletRequest(HttpServletRequest hsr) {
        this.hsr=hsr;
    }
}

 
Run: If you have successfully and carefully created everything mentioned above now you can have a directory structure as :


Now right click on the projects root directory and click Run. Here is what the welcome or index page will look like.

Download complete program from
here