This chapter will teach you how to use Struts2's application to send emails. For this exercise, you need to download and install mail.jar from JavaMail API 1.4.4 and place the mail.jar file in the WEB-INFlib folder, and then continue to follow the standard steps to create actions, views, and configuration files.
Create an action:
The next step is to create an Action method and send an email. Let's create a new class called Emailer.java with the following content.
package com.yiibai.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 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) { Emailer.properties = properties; }}You can see that in the above source code, Emailer.java has the corresponding properties of the email.jsp page given below in the form. These properties
Have we considered any validation of each of the above attributes, and the validation will be added in the next chapter. Now let's look at the execute() method. The execute() method uses the javax mail library to send an email, using the provided parameters. If the message is sent, the action returns SUCCESS, otherwise it returns ERROR.
Create a home page:
Let's write the JSP file of the home page index.jsp, which will be used to collect information about emails, as mentioned above:
<%@ 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 form below uses Google's SMTP server. So you need to enter a gmail username and password </em> <form action="emailer" 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>
Create a view:
We will use the success.jsp of the JSP file to return SUCCESS in the case where the action is called, but in the case where ERROR occurs, we will have another view that the file is returned 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 Success</title></head><body> Your email to <s:property value="to"/> was sent successfully.</body></html>
The following will be in an error case, return the view file error.jsp 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 Error</title></head><body> There is a problem sending your email to <s:property value="to"/>.</body></html>
Configuration file:
Now let's combine all of this with the configuration file of struts.xml as follows:
<?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" method="execute"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package></struts>
Here is the content in 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" 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 gives the following picture:
Enter the required information and click the "Send Email" button. If all goes well, you should see the following page:
If the three SSH frameworks are used together, I will give you an example here, but in addition to the frameworks of struts and spring, mail.jar, activation.jar is also required.
1) First configure bean in the applicationContext.xml file
<bean id="mailSender"> <property name="host" value="host"/> <property name="username" value="username"/> <property name="password" value="password"/> </bean><bean id="sendMailAction" singleton="false"> <property name="mailSender"><ref bean="mailSender"/> </property></bean>
2) Implement the java class code for sending emails
protected JavaMailSenderImpl mailSender;public class SendMailAction extends ActionSupport{public void setMailSender(JavaMailSenderImpl mailSender) { this.mailSender = mailSender;}public void sendMail() throws Exception {1: Simple email
protected JavaMailSenderImpl mailSender;public class SendMailAction extends ActionSupport{public void setMailSender(JavaMailSenderImpl mailSender) { this.mailSender = mailSender;}public void sendMail() throws Exception { 2: Send HTML mail
//Create email messages, send simple emails and html emails MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); //Set the recipient and sender messageHelper.setTo("[email protected]"); messageHelper.setFrom("[email protected]"); messageHelper.setSubject("Test HTML mail!"); //true Message messageHelper.setText("<html><head></head><body><h1>hello!!zhangjian</h1></body></html>",true); //Send email senderImpl.send(mailMessage);3: Nested pictures in this test email
//Create email messages, send simple emails and html emails MimeMessage mailMessage = senderImpl.createMimeMessage(); //Note that the boolean here can only nest images when it is true. When building MimeMessageHelper, the given value is true to enable. Multipart mode MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); //Set the recipient, sender messageHelper.setTo("[email protected]"); messageHelper.setFrom("[email protected]"); messageHelper.setSubject("Nested images in test mail!!"); //true Indicates the message in HTML format messageHelper.setText("<html><head></head><body><h1>hello!!zhangjian</h1>" + "<img src="/" mce_src="/""cid:aaa/"//</body></html>",true); FileSystemResource img = new FileSystemResource(new File("c:/aaa.jpg")); messageHelper.addInline("aaa",img); //Send email senderImpl.send(mailMessage); }}