Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Struts framework to send an email using gmail account

In this article, we will learn the requirements to send an email and the process to send email using gmail mail server.

Every web application needs to send an email as a response for an activity being performed against a request made by client. To send an email, we are required a mail server url and communication port to send email.

In this article, we will be using gmail mail server that sends email using port number 465. A struts framework is used to create web application and provides an api to send emails.

Send an email using gmail mail server using Struts Framework in Detail:

To send an email, first we need to configure a gmail mail server setting into our web application using a struts framework action. Now, we are required to place necessary email information that are required to send an email like sender email id, password, receiver id, subject of the email, and body of the email. These are defined as action class variables. Hence, create their getter() and setter() methods respectively.

Listing 1: SendEmail Action Class

package com.ajo.actions;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.opensymphony.xwork2.ActionSupport;

public class EmailSender extends ActionSupport {

   private String from;
   private String password;
   private String to;
   private String subject;
   private String body;

   static Properties properties = new Properties();
   static
   {
      properties.put("mail.smtp.host", "smtp.gmail.com");
      properties.put("mail.smtp.socketFactory.port", "465");
      properties.put("mail.smtp.socketFactory.class",
                     "javax.net.ssl.SSLSocketFactory");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.port", "465");
   }

   public String execute() 
   {
      String ret = SUCCESS;
      try
      {
         Session session = Session.getDefaultInstance(properties,  
            new javax.mail.Authenticator() {
            protected PasswordAuthentication 
            getPasswordAuthentication() {
            return new 
            PasswordAuthentication(from, password);
            }});

         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.setRecipients(Message.RecipientType.TO, 
            InternetAddress.parse(to));
         message.setSubject(subject);
         message.setText(body);
         Transport.send(message);
      }
      catch(Exception e)
      {
         ret = ERROR;
         e.printStackTrace();
      }
      return ret;
   }

   public String getFrom() {
      return from;
   }

   public void setFrom(String from) {
      this.from = from;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public String getTo() {
      return to;
   }

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

   public String getSubject() {
      return subject;
   }

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

   public String getBody() {
      return body;
   }

   public void setBody(String body) {
      this.body = body;
   }

   public static Properties getProperties() {
      return properties;
   }

   public static void setProperties(Properties properties) {
      EmailSender.properties = properties;
   }
}

In the above code, we used a javax.mail api to send an email and create an action class named SendEmail that extends ActionSupport class defined in com.opensymphony.xwork2 package. We defined a static block that assigned a properties class object to gmail mail server settings as follows:

static Properties properties = new Properties();
   static
   {
      properties.put("mail.smtp.host", "smtp.gmail.com");
      properties.put("mail.smtp.socketFactory.port", "465");
      properties.put("mail.smtp.socketFactory.class",
                     "javax.net.ssl.SSLSocketFactory");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.port", "465");
   }

In the next step, we define a execute() method that defined a Session class object using properties type object and Authenticator class of javax.mail package. In the next step, we defined a Message class object that configured a message that was being sent. A static method send() of class Transport was used to send this email that accepted Message class object as parameter.

Now create a user interface to login into the gmail account. This account will be used to send an email to receiver. An email will be sent to the given email address in the text field of index.jsp.

Listing 2: index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Gmail Email Sender Form</title>
</head>
<body>
   This page will accept gmail account information and will login into the account to send an email to the given email address into the “To” field.
   <form action="emailSender" method="post">
   <label for="from">From</label><br/>
   <input type="text" name="from"/><br/>
   <label for="password">Password</label><br/>
   <input type="password" name="password"/><br/>
   <label for="to">To</label><br/>
   <input type="text" name="to"/><br/>
   <label for="subject">Subject</label><br/>
   <input type="text" name="subject"/><br/>
   <label for="body">Body</label><br/>
   <input type="text" name="body"/><br/>
   <input type="submit" value="Send Email"/>
   </form>
</body>
</html>

In the above code, a html form was used to send an email using gmail mail account that accept a gmail account id and password, recipient address, subject and body of the email. A submit button was created to submit email login information and email sending information.

Once a html form is submitted, it will hits an action class using struts.xml configuration file. It will hit “emailer” action in the struts.xml file.

Listing 3: struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <package name="default" extends="struts-default">
   	  <default-action-ref name="index"></default-action-ref>
   	  <action name = "index">
   	  	<result>index.jsp</result>
   	  </action>
      <action name="emailSender" 
         class="com.ajo.actions.EmailSender"
         method="execute">
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>
   </package>
</struts>

The above code defines a tag to define the xml version and encode type and defines the struts document type definition. The <struts> tag is used to configure the struts web application and accept an action named “emailSender” defined in the sub – tag <action> of <package> tag that is the sub – tag of <struts> tag. If email is successfully sent, a success.jsp jsp file is loaded by web server as a response to user, otherwise it loads the error.jsp jsp page.

Listing 4: success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Email Sent</title>
</head>
<body>
   Your email to <s:property value="to"/> has been sent successfully. Thank you! :-)
</body>
</html>

The above code creates a web document to inform the user that an email has been sent successfully.

Listing 5: error.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Email Sending Error</title>
</head>
<body>
   It seems that there is a problem sending your email to <s:property value="to"/>. Please check for credentials.
</body>
</html>

The above code creates a html document to the user that informs, there is an error, while sending your email to the given email address.

To run this web application, there is a main configuration file that is web.xml file (a web application deployment descriptor for the web or application server). It manages incoming requests to the server for the application and transfers it to the struts.xml configuration file.

Listing 6: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

The above code uses a filter dispatcher class to transfer all the incoming request to struts.xml configuration file.

User Interface for Email Sender

Figure 1: User Interface for Email Sender

Above figure shows an interface to send an email.

emailSender action loads a success.jsp view, if email is sent successfully

Figure 2: emailSender action loads a success.jsp view, if email is sent successfully

If an email has been sent successfully, success view is loaded.

emailSender loads error.jsp, if there is an error while sending email

Figure 3: emailSender loads error.jsp, if there is an error while sending email

This pages is loaded, if there is something is wrong, while sending an email.

Directory Structure

Figure 4: Directory Structure

Above figure shows the directory structure of the application.

Conclusion:

In this article, we learn:

  • What are the requirements to send an email?
  • How do we send email using gmail mail server?


Have more than 5 years experience about Java, .Net, C and C++.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login