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.


JDK 1.6
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.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
id="WebApp_ID" version="3.0">


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.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts2 - Send Email</title>
<s:if test="hasActionErrors()">
<s:actionerror />
<s:if test="hasActionMessages()">
<s:actionmessage />
<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>


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.


<?xml version="1.0" encoding="UTF-8"?>
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
<!-- 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>


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

package in.webtuts.actions;

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";
// 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("", "");
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.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'
//set email subject
// set email message

// 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
// add the whole content
// required for file

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

// send the email


} catch (MessagingException e) {



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.

package in.webtuts.actions;


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
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;

// action method
public String execute() throws Exception {
// send the email
SendEmail.sendEmail(emailToAddress, emailSubject, emailBodyText, file,
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
public void validate() {
if (emailToAddress == null) {
String errorMsg = "You must provide To Email Address!";
if (emailSubject == null) {
String errorMsg = "You must provide Email Subject!";
if (emailBodyText == null) {
String errorMsg = "You must provide Email Message!";
if (file == null) {
String errorMsg = "You must select a file!";



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 from with Subject 'Sending Email with Attachment'.


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


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 *