JavaEmail testing with GreenMail

Below images are representing how application is connecting to mail service and how we can test mailservice with GreenMail? Below I have taken example for development environment.

DEV environment structure for MailService

Java Mail structure


Now will see the structure for Greenmail with JavaMail, How we can test JavaMail with GreenMail:

Java Mail with greenmail structure


Steps:
  • First using test configuration Greenmail server will be started.
  • Using same test configuration, JavaMail needs to be setup.
  • After GreenMail server startup, need to execute JavaMail method
  • After execution result needs to validate using Assert in JUNIT

Sample code to test Email with Greenmail

1. AppConfig.java
This is my actual class which is having connectivity with JavaMail.
package com.village.springEmailTest.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;

@Configuration@ImportResource(value = "classpath:/spring/appXMLContext.xml")
@PropertySource(value = "classpath:/properties/application.properties")
public class AppConfig {
	
	@Beanpublic JavaMailSenderImpl emailSender(@Value("${email.host}") String emailHost,
			@Value("${email.port}") Integer emailPort,
			@Value("${email.username}") String username,
			@Value("${email.pass}") String password){     
		
			JavaMailSenderImpl emailSender = new JavaMailSenderImpl();         
			emailSender.setHost(emailHost);         
			emailSender.setPort(emailPort);         
			emailSender.setUsername(username);         
			emailSender.setPassword(password);         
			//emailSender.setDefaultEncoding("UTF_8");         
			Properties mailProps = new Properties();         
			mailProps.setProperty("mail.transport.protocol","smtp");         
			mailProps.setProperty("mail.smtp.auth","true");         
			mailProps.setProperty("mail.smtp.starttls.enable","true");         
			mailProps.setProperty("mail.debug","false");         
			emailSender.setJavaMailProperties(mailProps);      
			returnemailSender;      
		}
}
	


2. appXMLContext.xml:
<?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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">
	<!--
		In Java @Configuration POJOs the @PropertySource isnot playing well
		with @Value. To resolve this we introducejust this reference that is
		doing the trick. No other dependency on XML configuration should be
		needed.
	-->
	<context:property-placeholder />
</beans>


3. application.properties::
email.host=smtp.gmail.com
email.port=25
email.username=yourGmailAtgmailDotcom
email.pass=yourPass


4. EmailTest.java:
package com.village.springEmailTest;

 import com.icegreen.greenmail.util.GreenMail;
 import com.icegreen.greenmail.util.GreenMailUtil;
 import com.icegreen.greenmail.util.ServerSetup;
 import com.icegreen.greenmail.util.ServerSetupTest;
 import com.village.springEmailTest.config.AppConfig;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.springframework.mail.SimpleMailMessage;
 import org.springframework.mail.javamail.JavaMailSenderImpl;
 import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
 import javax.annotation.Resource;
 import javax.mail.Message;
 import javax.mail.MessagingException; 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue; 
 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(classes = AppConfig.class)
 public class EmailTest {   
	 @Resource   
	 private JavaMailSenderImplemailSender;   
	 private GreenMailtestSmtp;   
	 
	 @Before   
	 public void testSmtpInit(){      
		 ServerSetup setup = new ServerSetup(65438, "localhost", "smtp");   
		 //Test properties      
		 testSmtp = new GreenMail(setup);      
		 //GreenMail server startup using test configuration      
		 testSmtp.start();      
		 //don't forget to set the same test port to EmailService, which is using by GreenMail      
		 emailSender.setPort(65438);      
		 emailSender.setHost("localhost");   
		 } 
	 @Test   
	 public void testEmail() throws InterruptedException, MessagingException {      
		 SimpleMailMessage message = new SimpleMailMessage();      
		 message.setFrom("test@sender.com");      
		 message.setTo("test@receiver.com");      
		 message.setSubject("test subject");      
		 message.setText("test message");      
		 //First we need to call the actual method of EmailSErvice      
		 emailSender.send(message);      
		 //Then after that using GreenMail need to verify mail sent or not      
		 assertTrue(testSmtp.waitForIncomingEmail(5000, 1));      
		 Message[] messages = testSmtp.getReceivedMessages();      
		 assertEquals(1, messages.length);      
		 assertEquals("test subject", messages[0].getSubject());      
		 String body = GreenMailUtil.getBody(messages[0]).replaceAll("=\r?\n", "");      
		 assertEquals("test message", body);   
	}    
	@After
	public void cleanup(){      
		testSmtp.stop();   
	}
 }


5. pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>SpringEmailTest</groupId>
	<artifactId>SpringEmailTest</artifactId>
	<version>1.0-SNAPSHOT</version>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies><!--Spring Dependencies-->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency><!--Testing Dependencies -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
		</dependency>
		<dependency>
			<groupId>com.icegreen</groupId>
			<artifactId>greenmail</artifactId>
			<version>${greenmail.version}</version>
		</dependency><!--Email Dependencies -->
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>${javax-mail.version}</version>
		</dependency>
	</dependencies>
	<properties>
		<java.version>1.6</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>3.2.2.RELEASE</spring.version>
		<junit.version>4.10</junit.version>
		<javax-mail.version>1.5.0</javax-mail.version>
		<greenmail.version>1.3.1b</greenmail.version>
	</properties>
</project>

Try executing the test class EmailTest, will get to know how this is working.