This tutorial shows how do we send email with attachment. This tutorial uses one input form where a user gives input for ‘Email To Address’ where the intended email will be sent, ‘Email Subject’, ‘Email Message’ and uploads one file which will be sent as an attachment with the email. This email sending example uses only gmail smtp server to send the mail. If you need only file upload example then you can search in the search box you will get file upload examples in Struts2, JSF2, Codeigniter2.

For testing purpose you can also send the email to yourself and after sending open your mailbox, you will find an email has arrived.

Prerequisites

JDK 1.6
Eclipse
Tomcat v7
Gmail Account
List of jars

send email with attachment using struts2

1. We create a Dynamic Web Project in Eclipse. The required project structure gets created. Now open the deployment descriptor file and modify it as follows.

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"
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>Struts2SendEmail</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>sendemail.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

2. Create one jsp file – sendemail.jsp – with the following inputs

To Address – where the email will be sent
Subject – subject of the email
Message – message to the email
File – file which will be attached to the email
Send Email – submit button for validating the input form and sending the email to the intended user

You must use enctype=”multipart/form-data” in the form tag otherwise you won’t be able to upload a file.

sendemail.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts2 - Send Email</title>
</head>
<body>
<s:if test="hasActionErrors()">
<s:actionerror />
</s:if>
<s:if test="hasActionMessages()">
<s:actionmessage />
</s:if>
<s:form action="sendEmail" method="post" enctype="multipart/form-data">
<s:textfield label="To Address" name="emailToAddress"></s:textfield>
<s:textfield label="Subject" name="emailSubject"></s:textfield>
<s:textarea label="Message" name="emailBodyText" rows="5" cols="50"></s:textarea>
<s:file label="File" name="file"></s:file>
<s:submit value="Send Email"></s:submit>
</s:form>
</body>
</html>

 

3. Now create struts configuration file which holds differenet configurations like action mapping, action name, action class mapping, input form, redirect to output page, different interceptors, constants etc. The below struts config is straight forward.

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- upload max file size limit -->
<constant name="struts.multipart.maxSize" value="10485760" />
<package name="default" namespace="/" extends="struts-default">
<!-- action and action class mapping -->
<action name="sendEmail" class="in.webtuts.actions.SendEmailAction">
<-- when form successfully submitted -->
<result name="success">/sendemail.jsp</result>
<!-- when we need to show the input form to the user -->
<result name="input">/sendemail.jsp</result>
<!-- we use default interceptor. interceptor are like cross cutting concern. -->
<interceptor-ref name="defaultStack">
<!-- maximum file size to be allowed to upload -->
<param name="maximumSize">10485760</param>
<!-- which files are allowed to be uploaded -->
<param name="allowedTypes">text/plain,image/jpeg,image/png,image/gif,image/pjpeg</param>
</interceptor-ref>
</action>
</package>
</struts>

 

4. Below class does the task of email sending process. It has one static void method sendMail which takes five arguments with meaningful name.

SendEmail.java

package in.webtuts.actions;

import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendEmail {

public static void sendEmail(final String emailToAddress,
final String emailSubject, final String emailBodyText,
final File file, final String fileName) {

// make sure you put your gmail address
final String username = "your gmail address@gmail.com";
// make sure you put your correct gmail address password
final String password = "your gmail password";

// We will put some properties for smtp configurations
Properties props = new Properties();

// do not change - start
props.put("mail.smtp.user", "username");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "25");
// props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable", "true");

props.setProperty("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
// do not change - end

// we authentcate using your gmail email and password and on successful we create the session
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

try {
// we create new message
Message message = new MimeMessage(session);
// set the from 'email address'
message.setFrom(new InternetAddress(username));
// set 'to email address'
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(emailToAddress));
//set email subject
message.setSubject(emailSubject);
// set email message
message.setText(emailBodyText);

// create MimeBodyPart for file attachment
MimeBodyPart messageBodyPart = new MimeBodyPart();
// we need this also for file attachment
Multipart multipart = new MimeMultipart();
// file data
DataSource source = new FileDataSource(file);
// attach file
messageBodyPart.setDataHandler(new DataHandler(source));
// set meaningful file name
messageBodyPart.setFileName(fileName);
// add the whole content
multipart.addBodyPart(messageBodyPart);
// required for file
message.setContent(multipart);

System.out.println("Sending Email to " + emailToAddress + " from "
+ username + " with Subject '" + emailSubject + "'.");

// send the email
Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
e.printStackTrace();
}

}
}

 

5. We will now look into the Action class which will do the actual upload of file and email sending process. We implement ServletContextAware to get the servlet related work done like uploading the file. The action class is just a simple POJO(Plain Old Java Object).

Note in this class, attribute names are same as on the input jsp form. So the mapping will be automatically done between form input names and java class attribute names.

SendEmailAction.java

package in.webtuts.actions;

import java.io.File;

import javax.servlet.ServletContext;

import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class SendEmailAction extends ActionSupport implements
ServletContextAware {

private static final long serialVersionUID = 1L;

// email subjuect
private String emailSubject;
// email message
private String emailBodyText;
// email to address
private String emailToAddress;

// input file
private File file;
// input file name - if the input type name is 'file' then file name should be 'fileFileName', if input type // name is 'f' then file name should be 'fFileName'
private String fileFileName;
// servlet context
private ServletContext servletContext;

public String getEmailSubject() {
return emailSubject;
}

public void setEmailSubject(String emailSubject) {
this.emailSubject = emailSubject;
}

public String getEmailBodyText() {
return emailBodyText;
}

public void setEmailBodyText(String emailBodyText) {
this.emailBodyText = emailBodyText;
}

public String getEmailToAddress() {
return emailToAddress;
}

public void setEmailToAddress(String emailToAddress) {
this.emailToAddress = emailToAddress;
}

public File getFile() {
return file;
}

public void setFile(File file) {
this.file = file;
}

public String getFileFileName() {
return fileFileName;
}

public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}

public ServletContext getServletContext() {
return servletContext;
}

// overridden method when we implement ServletContextAware
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}

// action method
@Override
public String execute() throws Exception {
// send the email
SendEmail.sendEmail(emailToAddress, emailSubject, emailBodyText, file,
fileFileName);
addActionMessage("Email with attachment successfully sent!");
// return to the success page which is the same page here
return SUCCESS;
}

// validate method is called before the execute method to validate the input fields
@Override
public void validate() {
if (emailToAddress == null) {
String errorMsg = "You must provide To Email Address!";
addActionError(errorMsg);
}
if (emailSubject == null) {
String errorMsg = "You must provide Email Subject!";
addActionError(errorMsg);
}
if (emailBodyText == null) {
String errorMsg = "You must provide Email Message!";
addActionError(errorMsg);
}
if (file == null) {
String errorMsg = "You must select a file!";
addActionError(errorMsg);
}
}

}

 

When we run the application we get the output on the browser.

Input form

send email with attachment using struts2

Fill in input form

send email with attachment using struts2

Send the email with attachment

send email with attachment using struts2

Output to the console when email is successfully sent.

Sending Email to soumitrajuster@gmail.com from soumitrajuster@gmail.com with Subject 'Sending Email with Attachment'.
Done

 

Thanks for your reading. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *