Sending Web Email from Spring

From Kb

Jump to: navigation, search

Contact Article Author | Blog of Article Author | FirstPartners.net Home | LinkedIn profile of Author

Other Spring Related Articles

Spring MVC | Maven Information | Hibernate | Sending Web Email from Spring | Spring Pointer to Log4j Configuration File | Cron Timer functionality using Spring and Quartz | Customising Spring Property File Loading

Setup Web Form and Send Email when Submitted

  • Setup Web Project
    • Import Spring Tag libraries
    • Use Spring 2 Jar


  • Use the following Spring Context
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!--
  - Application context definition for "springapp" DispatcherServlet.
  -->
<beans>
        <!-- Let Spring Framework know what the main controller class is -->
	<bean id="BctEmailServlet" class="ie.iib.email.BctEmailServlet">
 
		<!-- Email Server Properties -->
		<property name="mailServer"><value>NAME-OF-MAILSERVER</value></property>
		<property name="username"><value></value></property> <!-- blank username means ignore -->
		<property name="password"><value></value></property> <!-- blank username means ignore -->
		<property name="port"><value>-1</value></property> <!-- Use Default -->
		<property name="protocol"><value>SMTP</value></property>
 
 
		<!-- Email Message Properties -->
		<property name="sendToEmailAddress"><value>test@address.com</value></property>
		<property name="replyToEmailAddress"><value>no-reply@Address.com</value></property>
		<property name="emailSubject"><value>Automated  Email</value></property>
 
		<!-- Set this to integrate with the rest of the BCT application -->
		<property name="successPage"><value>success</value></property>
		<property name="errorPage"><value>error</value></property>
 
 	</bean>
 
    <!-- Maps Post and Get Requests onto the main Controller defined above -->
	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/simple.htm">EmailServlet</prop>
			</props>
		</property>
 
	</bean>
 
    <!-- Spring Class to allow the framework to decide what JSP view page to show -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
		<property name="prefix"><value>/</value></property>
		<property name="suffix"><value>.jsp</value></property>
	</bean>
</beans>
  • Create the following Servlet
/*
 * Built using software copied from http://red-piranha.sourceforge.net
 *
 * This product includes software developed by the
 * Apache Software Foundation (http://www.apache.org)."
 *
 * This product includes software developed by the
 * Spring Framework Project (http://www.springframework.org)."
 *
 */
package net.fp.rp.email;
 
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
 
 
/**
 * Main point of entry into the system for the web interface.  This class will
 * be responsable for dispatching the request   and translate the request to
 * be interpreted by the KnowledgeSpherreManager-controller
 *
 * Normally we would use one of the more sophisticated controllers available in Spring
 *
 * Using Spring means that (a) we have a default constructor and (b) we can test
 * methods like 'sendEmail' using standard Junit tests
 *
 * @author Paul Browne
 * @version 1.4
 */
public class GenericEmailServlet extends AbstractController {
 
	/** Get method name */
    public static final String METHOD_GET = "GET";
 
    //Server settings
    private String mailServer="";
    private String username="";
    private String password="";
    private int port=-1; //use default (will normally set it to 25)
    private String protocol="";
 
 
 
    /** The result views */
    private String successPage = "";
 
    private String errorPage ="";
 
 
    //Email message settings
    private String sendToEmailAddress="";
 
    private String emailSubject="";
 
    private String replyToEmailAddress="";
 
 
    /** Logger for this class and subclasses */
    protected final Logger log = Logger.getLogger(getClass());
 
    /**
     * Process the request and return a ModelAndView object which the
     * DispatcherServlet will render.
     *
     * @param request current HTTP request
     * @param response current HTTP response
     *
     * @return a ModelAndView to render, or null if handled directly
     *
     * @throws Exception in case of errors
     */
    public ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
 
 
    	//Local variables
    	String returnPage = getSuccessPage();
 
    	log.debug("BctEmailServlet handleRequest Start");
 
 
 
    	try {
 
 
    		//Get the incoming values
    		Map incomingValues =request.getParameterMap();
 
    		//try to send the email if we have incoming values
    		//(ie this is not the initial , show web page , request
    		if(incomingValues.size()>0){
 
    			//Create the email message
    			SimpleMailMessage email = createEmail(incomingValues);
    			log.debug("Email Message:"+email);
 
    			//Send the email
    			sendEmail(email);
 
 
    		} else {
    			log.debug("No incoming Values on Request , redirecting to Success / email form");
    		}
 
    	} catch (Exception e){
    		log.warn("BCT Application Exception - forwarding to error page",e);
    		returnPage = getErrorPage();
    	}
 
 
 
    	log.debug("About to forward to page:"+returnPage);
    	return new ModelAndView(returnPage);
 
    }
 
    /**
	 * Send the Email
	 * We use the Spring Email sender components internally, no value (yet)
	 * in refactoring these out.
	 * @param email
	 */
	void sendEmail(SimpleMailMessage email) {
 
 
		//Create and setup the mail sender component
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setHost(mailServer);
		mailSender.setPort(port);
		mailSender.setProtocol(protocol);
 
		//Only set if username not blank
		if(!"".equals(username)){
			mailSender.setUsername(username);
			mailSender.setPassword(password);
 
			//We need this setting for force Javamail to pass the login
			Properties props = new Properties();
			props.setProperty("mail.smtp.auth", "true");
			mailSender.setJavaMailProperties(props);
 
		}
 
		log.debug("About to send email using:"+mailSender);
		mailSender.send(email);
 
 
	}
 
	/**
     * Send the email , using the incoming values
     * @param inValues
     * @throws Exception
     */
	SimpleMailMessage createEmail(Map inValues) throws Exception{
 
    	//null check
    	if (inValues==null){
    		throw new Exception("incoming Parameter Map was null");
    	}
 
    	//Put the standard values onto the message
    	SimpleMailMessage mailMessage = new SimpleMailMessage();
    	mailMessage.setFrom(replyToEmailAddress);
    	mailMessage.setTo(sendToEmailAddress);
    	mailMessage.setSubject(emailSubject);
 
 
    	//Loop and build up the message
    	Iterator loopList= inValues.keySet().iterator();
    	Object tmpKey = null;
    	Object tmpValue=null;
    	StringBuffer emailText = new StringBuffer();
    	String[] tmpStringArray=null;
 
    	log.debug("Number of Incoming Values:"+inValues.size());
 
    	while(loopList.hasNext()){
    		tmpKey = loopList.next();
    		tmpValue = inValues.get(tmpKey);
 
 
 
    		if(tmpValue instanceof String[]){
 
    			emailText.append(tmpKey+" :");
    			tmpStringArray =(String[])tmpValue;
    			for(int a=0;a<tmpStringArray.length;a++){
    				emailText.append(","+tmpStringArray[a]);
    			}
 
    			//add a new line
 
    			emailText.append("/n");
 
 
    		} else {
    			emailText.append(tmpKey+" : "+tmpValue+"/n");
    		}
 
    	}
 
    	//Set the email Text
    	log.debug(emailText);
    	mailMessage.setText(emailText.toString());
 
    	return mailMessage;
 
    }
 
 
 
	/**
	 * @param errorPage the errorPage to set
	 */
	public void setErrorPage(String errorPage) {
		this.errorPage = errorPage;
	}
 
 
	/**
	 * @return the errorPage
	 */
	public String getErrorPage() {
		return errorPage;
	}
 
 
	/**
	 * @param successPage the successPage to set
	 */
	public void setSuccessPage(String successPage) {
		this.successPage = successPage;
	}
 
 
	/**
	 * @return the successPage
	 */
	public String getSuccessPage() {
		return successPage;
	}
 
 
 
 
	/**
	 * @param mailServer the mailServer to set
	 */
	public void setMailServer(String mailServer) {
		this.mailServer = mailServer;
	}
 
 
 
 
	/**
	 * @return the mailServer
	 */
	public String getMailServer() {
		return mailServer;
	}
 
 
 
 
	/**
	 * @param sendToEmailAddress the sendToEmailAddress to set
	 */
	public void setSendToEmailAddress(String sendToEmailAddress) {
		this.sendToEmailAddress = sendToEmailAddress;
	}
 
 
 
 
	/**
	 * @return the sendToEmailAddress
	 */
	public String getSendToEmailAddress() {
		return sendToEmailAddress;
	}
 
 
 
 
	/**
	 * @param emailSubject the emailSubject to set
	 */
	public void setEmailSubject(String emailSubject) {
		this.emailSubject = emailSubject;
	}
 
 
 
 
	/**
	 * @return the emailSubject
	 */
	public String getEmailSubject() {
		return emailSubject;
	}
 
	/**
	 * @param replyToEmailAddress the replyToEmailAddress to set
	 */
	public void setReplyToEmailAddress(String replyToEmailAddress) {
		this.replyToEmailAddress = replyToEmailAddress;
	}
 
	/**
	 * @return the replyToEmailAddress
	 */
	public String getReplyToEmailAddress() {
		return replyToEmailAddress;
	}
 
	/**
	 * @param username the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}
 
	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}
 
	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
 
	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}
 
	/**
	 * @param port the port to set
	 */
	public void setPort(int port) {
		this.port = port;
	}
 
	/**
	 * @return the port
	 */
	public int getPort() {
		return port;
	}
 
	/**
	 * @param protocol the protocol to set
	 */
	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}
 
	/**
	 * @return the protocol
	 */
	public String getProtocol() {
		return protocol;
	}
 
 
}
Personal tools