Required jar files | |
mail.jar | |
spring-beans-3.2.0.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-context-support-3.2.0.RELEASE.jar spring-core-3.2.0.RELEASE.jar spring-expression-3.2.0.RELEASE.jar spring-web-3.2.0.RELEASE.jar spring-webmvc-3.2.0.RELEASE.jar | |
commons-logging-1.1.1.jar | |
commons-fileupload-1.2.2.jar | |
commons-io-2.3.jar |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Spring MVC - Email</title> </head> <body> <center> <h1>Spring MVC - Send e-mail with attachments</h1> <form method="post" action="sendEmail.do" enctype="multipart/form-data"> <table border="0" width="80%"> <tr> <td>Email To:</td> <td><input type="text" name="mailTo" size="65" /></td> </tr> <tr> <td>Subject:</td> <td><input type="text" name="subject" size="65" /></td> </tr> <tr> <td>Message:</td> <td><textarea cols="50" rows="10" name="message"></textarea></td> </tr> <tr> <td>Attach file:</td> <td><input type="file" name="attachFile" size="60" /></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="Send E-mail" /> </td> </tr> </table> </form> </center> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="net.codejava.spring" /> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com" /> <property name="port" value="587" /> <property name="username" value="youremail" /> <property name="password" value="yourpassword" /> <property name="javaMailProperties"> <props> <prop key="mail.transport.protocol">smtp</prop> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop> </props> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- max upload size in bytes --> <property name="maxUploadSize" value="20971520" /> <!-- 20MB --> <!-- max size of file in memory (in bytes) --> <property name="maxInMemorySize" value="1048576" /> <!-- 1MB --> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">Error</prop> </props> </property> </bean> </beans>There are four beans declared in this configuration which draws our attention:
package net.codejava.spring; import java.io.IOException; import java.io.InputStream; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller @RequestMapping("/sendEmail.do") public class SendEmailAttachController { @Autowired private JavaMailSender mailSender; @RequestMapping(method = RequestMethod.POST) public String sendEmail(HttpServletRequest request, final @RequestParam CommonsMultipartFile attachFile) { // reads form input final String emailTo = request.getParameter("mailTo"); final String subject = request.getParameter("subject"); final String message = request.getParameter("message"); // for logging System.out.println("emailTo: " + emailTo); System.out.println("subject: " + subject); System.out.println("message: " + message); System.out.println("attachFile: " + attachFile.getOriginalFilename()); mailSender.send(new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper messageHelper = new MimeMessageHelper( mimeMessage, true, "UTF-8"); messageHelper.setTo(emailTo); messageHelper.setSubject(subject); messageHelper.setText(message); // determines if there is an upload file, attach it to the e-mail String attachName = attachFile.getOriginalFilename(); if (!attachFile.equals("")) { messageHelper.addAttachment(attachName, new InputStreamSource() { @Override public InputStream getInputStream() throws IOException { return attachFile.getInputStream(); } }); } } }); return "Result"; } }This Spring controller (marked by @Controller annotation) is responsible for handling e-mail form’s submission which is configured by two @RequestMapping annotations.The second parameter of the sendEmail() method is annotated by @RequestParam annotation which maps the form field attachFile to a CommonsMultipartFile object that represents an upload file.In the method sendEmail(), we capture input fields from the e-mail form (mailTo, subject and message) and send an e-mail by invoking the send() method on the mailSender object (which is automatically injected to this controller via the autowired property mailSender).The send() method is passed with an anonymous class which implements the MimeMessagePreparator interface and implements the prepare() method. In the prepare() method we construct the e-mail message object with help of the MimeMessageHelper class and invoke its addAttachment() method to attach the upload file as attachment to the e-mail. This method reads data of upload file from the input stream which is returned by the attachFile object.Finally, the controller redirects the user to a result page whose logical name is “Result”.NOTE: if the user doesn’t pick up a file to attach, the attachName will be empty, so that there is a check to make sure we only add attachment if the upload file available.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Send e-mail result</title> </head> <body> <center> <h2>Thank you, your email has been sent.</h2> </center> </body> </html>This page simply shows a successful message after the file was uploaded and the e-mail has been sent.And code of the error page (Error.jsp) would look like:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Error</title> </head> <body> <center> <h2>Sorry, the email was not sent because of the following error:</h2> <h3>${exception.message}</h3> </center> </body> </html>This page displays a detailed error message in case of exceptions thrown, such as the upload file’s size exceeds the limit or SMTP setting is wrong.
<?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>EmailAttachSpringMVC</display-name> <servlet> <servlet-name>SpringController</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringController</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>EmailForm.jsp</welcome-file> </welcome-file-list> </web-app>As usual, that declares the Spring controller servlet to intercept requests coming to the application, and specifies the default page (EmailForm.jsp) when accessing the application.You can download this application in an Eclipse project or a deployable WAR file, under the attachment section.