Send Email Spring

Send Email Spring

Java provides API to send email easily but it takes time to write program and include all configuration information. Spring makes very easy to send email as its provides all the boiler plates codes only thing you will have to is just use the API and call its method to send an email. In this example I will show how easy to send email using Spring framework.

  • To understand completely I will create simple maven project name: SpringSendEmail as complete project structure is below:

Send Email Spring

  • pom.xml: It shows what are dependencies you will have to add:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.JavaHonk.report</groupId>
  <version>0.0.1-SNAPSHOT</version>
  
    <properties>
		<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
		<org.apache.log4j.version>2.1</org.apache.log4j.version>
		<javax.mail.version>1.4.6</javax.mail.version>		
	</properties>
	
	<dependencies>
	
	<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Various Application Context utilities, including EhCache, JavaMail, 
			Quartz, and Freemarker integration Define this if you need any of these integrations -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<!-- Log4j -->
        <dependency>
        	<groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${org.apache.log4j.version}</version>
		</dependency>
        
        <dependency>
        	<groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${org.apache.log4j.version}</version>
		</dependency>
		
		<!-- mail components -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>${javax.mail.version}</version>
		</dependency>
		
	</dependencies>
	
	
	<artifactId>SpringSendEmail</artifactId>
</project>
  • spring-context.xml: As we are using Spring framework and this is heart of the application from where we are loading all our beans and configuration. It’s self explanatory as I assumed you have knowledge of Spring framework.
<?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"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.javhaonk" />
	
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>JavaHonk.properties</value>								
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true"/>
		<property name="ignoreResourceNotFound" value="true"/>
	</bean>
	
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    	<property name="host" value="${smtp.host}"/>
	</bean>

	<bean id="errorTemplate" class="org.springframework.mail.SimpleMailMessage">
	    <property name="from" value="${from_address}"/>
	    <property name="to" value="${to_address}"/>
	    <property name="subject" value="Message from error tempate: There is an error sending email"/>
	</bean> 
	
	<bean id="successTemplate" class="org.springframework.mail.SimpleMailMessage">
	    <property name="from" value="${from_address}"/>
	    <property name="to" value="${to_address}"/>
	    <property name="subject" value="${subject}"/>
	</bean> 
	
	<bean id="mailHelper" class="com.javahonk.report.util.MailHelper" />	
	
	<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage" />
	
	
	
</beans>
  • JavaHonk.properties: I am also including properties file where you can keep all email related properties ourside of the application so that if you want to change properties based on environments.
smtp.host=localhost
from_address=From_javahonk@javahonk.com
to_address=To_javahonk@javahonk.com
subject=Send mail using Spring
  • log4j2.xml: Mandatory for any project I am also including its configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" shutdownHook="disable">

	<Properties>
		<Property name="envrionment.target">DEV</Property>
	</Properties>

	<Properties>
		<Property name="logging.dir">./</Property>
	</Properties>

	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</Console>

		<RollingFile name="RollingFile"
			fileName="logs/rolling-file.log"	filePattern="${sys:logging.dir}/logs/rolling-file-%d{yyyy-MM-dd}-%i.log">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
			<!-- TODO:Change to time based policy -->
			<Policies>
				<TimeBasedTriggeringPolicy interval="1"	modulate="true" />
				<SizeBasedTriggeringPolicy size="100 MB" />
			</Policies>
			<DefaultRolloverStrategy max="4" />
		</RollingFile>
	</Appenders>

	<Loggers>
		<Root level="info">
			<AppenderRef ref="Console" />
			<!-- <AppenderRef ref="file" /> -->
			<AppenderRef ref="RollingFile" />
		</Root>
	</Loggers>
</Configuration>
  • MailHelper.java: Main class to send an email:
package com.javahonk.report.util;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.mail.internet.MimeMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class MailHelper {
	
	private static final Logger logger = LogManager.getLogger(MailHelper.class.getName());
	
	@Autowired
	private MailSender mailSender;
	
	@Autowired
	@Qualifier("mailSender")
	private JavaMailSender javaMailSender;
	
	public void sendMimeMessage(
			final String mimeMessage,
			final String fromAddress,
			final List<String> toAddresses,
			final String mailSubject,
			final Map<String, File> attachments){
		
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			
			@Override
			public void prepare(MimeMessage message) throws Exception {
				
				MimeMessageHelper helper = new MimeMessageHelper(message, true);
				
				for(String address : toAddresses){
					helper.addTo(address);
				}
				
				helper.setFrom(fromAddress);
				helper.setSubject(mailSubject);
				
				if(attachments!=null){
					
					for(Entry<String, File> attachment : attachments.entrySet()){
						
						helper.addAttachment(attachment.getKey(), attachment.getValue());
					}
					
				}
				
				helper.setText(mimeMessage);
			}
		};
		
		try{
			
            this.javaMailSender.send(preparator);
            
        }
        catch (MailException ex) {
        	
        	logger.error("Failed to send email for templated message:" +
					"\nFrom:" + fromAddress +
					"\nTo:" + toAddresses +
					"\nMessage:" + mimeMessage, ex);
        }
		
	}

	public void sendSimpleMailMessage(
			SimpleMailMessage templateMessage,
			String message){
		
		SimpleMailMessage msg = new SimpleMailMessage(templateMessage);
		
		msg.setText(message);
		
		try{
			
            this.mailSender.send(msg);
            
        }
        catch (MailException ex) {
        	
			logger.error("Failed to send email for templated message:" +
					"\nFrom:" + templateMessage.getFrom() +
					"\nTo:" + templateMessage.getTo() +
					"\nMessage:" + templateMessage.getText(), ex);

        }
		
	}
	
}
  • SendEmail.java: Test class to send an email:
package com.javahonk.report;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;

import com.javahonk.report.util.MailHelper;

public class SendEmail {
	
	private static final Logger logger = LogManager.getLogger(SendEmail.class);

	public static void main(String[] args) {
		
		logger.info("Application is starting");
		
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
		
		SimpleMailMessage successTemplate = (SimpleMailMessage)context.getBean("successTemplate");
		
		SimpleMailMessage errorTemplate = (SimpleMailMessage)context.getBean("errorTemplate");
		
		Map<String, File> attachments = new HashMap<String, File>();
		attachments.put("JavaHonk.xlsx", new File("JavaHonk.xlsx"));
		
		List<String> toAddress = new ArrayList<String>();
		toAddress.add("To_javahonk@javahonk.com");		
		
		
		//Send mail with attachment
		context.getBean(MailHelper.class).sendMimeMessage(
				"Message: Reponse sent successfully",
				"From_javahonk@javahonk.com", toAddress,
				"Subject: Send email using Spring framework", attachments);
		
		//Simple message configure in spring context file
		context.getBean(MailHelper.class).sendSimpleMailMessage(successTemplate, "Java Honk Test Message");
		
		//Error template to send message in case or error
		context.getBean(MailHelper.class).sendSimpleMailMessage(errorTemplate, "Java Honk Error Message");
		
		((AbstractApplicationContext) context).close();

	}

}
  • To test this application you could use your company SMTP host if due to some reason SMTP host is not available you could use FakeSMTP server which you could download from here. In this demo I will also use FakeSMTP server to test email functionality. To test please run SendEmail.java as Java application and it run successfully you will below out on FakeSMTP server as below:

Send Email Spring

In example above we have sent three message as below:

  • Email with XLS sheet attachment
  • Simple message configure in spring context file
  • Error template to send message in case of error

For more information please visit Spring official site here

download Download Project: SpringSendEmail

Leave a Reply

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