Introduction🧑🏻🎓
You most likely found this article because you wish to use Struts 2 to send emails. Manual email sending is a time-consuming process and prone to error, but Struts 2 makes it simple via automation.
In the following article, we will study in detail on how to send an email using your Struts 2 application.
Pre-requisites🧐
To complete this exercise, you must first download and install the mail.jar file from JavaMail API 1.4.4, place it in your WEB-INF/lib folder, and create action, view, and configuration files as usual.
Steps to Create the Application🧐
Create Action🤔
Making an Action method that handles sending the email is the next step. Let's add the following to a new class we'll call Emailer.java.
package com.codingninjas.struts2;
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 Emailer extends ActionSupport {
private String mailFrom; //from
private String userPassword;
private String mailTo;
private String mailSubject;
private String mailBody;
static Properties properties = new Properties();
static {
properties.put("mail.smtp.host", "ninja.gmail.com");
properties.put("mail.smtp.socketFactory.port", "475");
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "475");
}
public String execute() {
String ret = SUCCESS;
try {
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication() {
return new
PasswordAuthentication(mailFrom, userPassword);
}
}
);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailFrom));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(mailTo));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
} catch(Exception e) {
ret = ERROR;
e.printStackTrace();
}
return ret;
}
public String getFrom() {
return mailFrom;
}
public void setFrom(String mailFrom) {
this.mailFrom = mailFrom;
}
public String getPassword() {
return userPassword;
}
public void setPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getTo() {
return mailTo;
}
public void setTo(String to) {
this.mailTo = mailTo;
}
public String getSubject() {
return mailSubject;
}
public void setSubject(String mailSubject) {
this.mailSubject= mailSubject;
}
public String getBody() {
return mailBody;
}
public void setBody(String mailBody) {
this.mailBody = mailBody;
}
public static Properties getProperties() {
return properties;
}
public static void setProperties(Properties properties) {
Emailer.properties = properties;
}
}
As displayed in the code above, Emailer.java has properties that correlate to the form attributes in the email.jsp page. These attributes are-
mailFrom- The sender's email address. We require a legitimate gtalk id since we are using Google's SMTP.
userPassword- The account's password from earlier.
mailTo- Whom should the email be sent to?
mailSubject- The Email's subject.
mailBody- The text of the email.
The fields mentioned above do not currently have any validations; Now, let's examine the execute() method. The execute() method sends an email with the specified arguments using the javax Mail package. Action returns SUCCESS if the mail is successfully sent; otherwise, it returns ERROR.
Create Main Page🤔
Let's create the index.jsp main page JSP file, which will be used to gather the aforementioned email-related data.
<%@ 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 Form</title>
</head>
<body>
<em>The SMTP server below utilizes Google.
Consequently, you must enter your Gmail username and password.
</em>
<form action = "emailer" method = "post">
<label for = "mailFrom">mailFrom</label><br/>
<input type = "text" name = "mailfrom"/><br/>
<label for = "userPassword">userPassword</label><br/>
<input type = "password" name = "userPassword"/><br/>
<label for = "mailTo">mailTo</label><br/>
<input type = "text" name = "mailTo"/><br/>
<label for = "mailSubject">mailSubject</label><br/>
<input type = "text" name = "mailSubject"/><br/>
<label for = "mailBody">mailBody</label><br/>
<input type = "text" name = "mailBody"/><br/>
<input type = "submit" value = "Send Email"/>
</form>
</body>
</html>
Create Views🤔
If the action returns SUCCESS, we will use the JSP file success.jsp; however, if the action returns an ERROR, we will use a different view file.
<%@ 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 is a Success</title>
</head>
<body>
The email to <s:property value = "mailTo"/> has been sent successfully.
</body>
</html>
The view file error.jsp will come next if an ERROR is received from the action.
<%@ 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 faces Error</title>
</head>
<body>
The email could not be sent to <s:property value = "mailTo"/> due to a problem.
</body>
</html>
Configuration Files🤔
Let's combine everything using the struts.xml setup file as shown below:
<?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>
<constant name = "struts.devMode" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "emailer"
class = "com.codingninjas.struts2.Emailer"
method = "execute">
<result name = "success">/success.jsp</result>
<result name = "error">/error.jsp</result>
</action>
</package>
</struts>
Following is the content of the web.xml file −
<?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>
Now, right-click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in Tomcat's webapps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen −
Click the Send Email button after entering the necessary information. If everything goes according to plan, the next page should appear.
Frequently Asked Questions
How to handle exceptions in Struts2?
Struts 2 uses the "exception" interceptor to make handling exceptions simple. You don't need to take any additional steps to configure the "exception" interceptor because it is already part of the default stack. It is available and prepared for usage right out of the box.
What should be the name of the xml file used for validation in struts?
The name of the xml file must be [action-class]-validation.xml.
What is the Struts2 validation framework?
The foundation of Struts is the validation framework, which helps the application run the rules for validation prior to calling the action method. To invoke the validate method, an Action class must extend the ActionSupport class.
What is XML-Based Validation in struts2?
A way of validating an action class involves putting an xml file next to it. More possibilities for validation are offered by Struts2's XML-based validation, including validation for email, numeric ranges, form fields, expressions, regexes, required conditions, requiredstrings, stringlengths, and others.
Which interceptor is responsible for file upload support?
A pre-defined interceptor named FileUpload interceptor is available through the org.apache.struts2.interceptor.FileUploadInterceptor class that is integrated into the defaultStack to enable file uploading in Struts.