Struts - SPLessons

Struts 2 Sending Mails

Home > Lesson > Chapter 23
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Struts 2 Sending Mails

Struts 2 Sending Mails

shape Description

Working with Struts 2 Sending Mails concept is always an interesting task to go with these concept user should know JAVA mail API. JavaMail API is the concept related to email through the JavaMail. By using JavaMail API sending, receiving, deleting, managing the email. JavaMail API is platform, protocol independent framework for to send or receive mail. JavaMail API also provides core classes for to define objects and used that objects to maintain a mail system. Here are some protocols which support the JavaMail API, they are as follows. SMTP: It is an acronym for the "Simple Mail Transfer Protocol", which issues a instrument to deliver the electronic mail(Email). An authentication is required in case of sending and receiving the emails through SMTP server which was provided by host server. An SMTP server also uses the Postcast server, ApacheJames server. POP: It is an acronym for the "Post Office Protocol", Which supports to receive the email. For each user POP supports the single mail box. POP is defined by RFC 1939. MIME: It is an acronym for the "Multiple Internet Mail Extension". It just explains the content transferred like attachments and which type of formatted message. IMAP: It is an acronym for the "Internet Message Access Protocol". It is an advanced one to receive the messages. For each user IMAP supports the multiple mail box and by multiple users the mail box shared. IMAP is defined in RFC 2060. NNTP: It is an acronym for the "Network News Transfer Protocol", it is the third party provider protocol.

shape Conceptual figure

Architecture for JavaMail API is shown below: From the above figure, the JavaMail API uses the java application to send, receive, compose the email. It also uses the Server Provider Interface (SPI) to provide the intermediate services to java application, because of this JavaMail API can deal with many protocols.

shape Example

Following is an example to send a mail in struts 2. MailAction.java [java] package com.splessons; 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 MailAction extends ActionSupport { private static final long serialVersionUID = 1L; 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) { MailAction.properties = properties; } }[/java] Struts 2 comes with an optional action interface (com.opensymphony.xwork2.Action). By implements this interface, it bring some convenient benefits. The serialVersionUID is a general adaptation identifier for a Serializable class. Deserialization utilizes this number to guarantee that a stacked class compares precisely to a serialized object. getDefaultInstance Get the default Session object. If a default has not yet been setup, a new Session object is created and installed as the default. welcome.jsp [java]<%@ 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> <input type="text" name="from"/> <label for="password">Password</label> <input type="password" name="password"/> <label for="to">To</label> <input type="text" name="to"/> <label for="subject">Subject</label> <input type="text" name="subject"/> <label for="body">Body</label> <input type="text" name="body"/> <input type="submit" value="Send Email"/> </form> </body> </html>[/java] Here labels have created to enter the data such as from, passwoed, to, body, submit, etc. success.jsp [java]<%@ 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>[/java] The property tag is used to get the property value from a class error.jsp [java] <%@ 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>[/java] This page will be called when the user get an error while sending an email. struts.xml [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> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="false" /> <constant name="struts.custom.i18n.resources" value="myapp" /> <package name="default" extends="struts-default" namespace="/"> <action name="emailer" class="com.dineshonjava.struts2.mail.action.MailAction" method="execute"> <result name="success">/success.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>[/xml] Where success is a predefined result type. action element is the sub component of package. It speaks to an activity to be conjured for the approaching request. It has name, class and method attributes. In the event that you don’t determine name property as a matter of course execute() technique will be summoned for the predetermined actiion class. Output When compile the code following is the output will be generated. When click on the button following success message will be displayed. Now check the mail.

Summary

shape Key Points

  • Struts 2 Sending Mails - All the jar files needs to be kept in lib folder.
  • Struts 2 Sending Mails - JAVA Mail API jar files needs to be inserted.
  • Struts 2 Sending Mails - Check the system SMTP protocol number and by default port number is 587.