Simple way to Send an Email using Spring MVC 5.x.x Framework – org.springframework.mail. javamail.JavaMailSenderImpl

Last updated
App Shah

Crunchify » Spring MVC and Spring Boot Tutorials » Simple way to Send an Email using Spring MVC 5.x.x Framework – org.springframework.mail. javamail.JavaMailSenderImpl

simple-way-to-send-an-email-using-spring-mvc-4-x-framework

There are quite a few articles you might have read on Crunchify on Spring MVC like Introduction to Spring MVC Framework, Hello World Spring MVC, Upload Multiple Files using Spring MVC, etc.

In this tutorial we will go over how to leverage org.springframework.mail.javamail.JavaMailSenderImpl library to send an email using Spring MVC 5.1.3.RELEASE.

Let’s get started:

Here is a final project structure. Make sure to create file accordingly.

Spring MVC 4.1.x send email project structure

Step-1

Create simple Maven Project CrunchifySpringMVC4SendEmailTutorial.

  • Select checkbox for “Create a simple project (skip archetype selection)” option
  • Provide all information similar to below diagram, i.e. Group Id, Artifact Id, Name and Description which we will use in next steps.

Create Spring MVC Maven Project

Step-2

Open pom.xml file and add 3 dependencies.

  1. spring-context
  2. spring-context-support
  3. javax.mail

Here is my complete pom.xml file.

<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>CrunchifySpringMVC4SendEmailTutorial</groupId>
	<artifactId>CrunchifySpringMVC4SendEmailTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>CrunchifySpringMVC4SendEmailTutorial</name>
	<description>Best way to send an email using Spring MVC 4.1.6 - Crunchify Tips</description>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.1.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>5.1.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.7</version>
		</dependency>
	</dependencies>
</project>

Step-3

Create Spring Bean file crunchify-bean.xml under src/main/resources folder.

Spring beans are configured using the traditional XML approach. In Spring MVC framework bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC (Inversion of Control) container.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:util="http://www.springframework.org/schema/util" 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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd 
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- this is your package structure where you create file CrunchifyEmailAPI.java 
		and CrunchifyEmailTest.java -->
	<context:component-scan base-package="crunchify.com.tutorials" />

	<!-- Production implementation of the JavaMailSender interface, supporting 
		both JavaMail MimeMessages and Spring SimpleMailMessages -->
	<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="<!-- Provide your Gmail ID -->" />
		<property name="password" value="<!-- Provide your Gmail Password -->" />

		<!-- The name of the property, following JavaBean naming conventions -->
		<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>
				<prop key="mail.debug">true</prop>
			</props>
		</property>
	</bean>
</beans>

Please make sure you update username and password field values with your real/actual values.

Step-4

Create API class CrunchifyEmailAPI.java annotation with @Service (org.springframework.stereotype.Service) under src/main/java folder.

package crunchify.com.tutorials;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

/**
 * @author crunchify.com
 * 
 */

@Service("crunchifyEmail")
public class CrunchifyEmailAPI {

	@Autowired
	private MailSender crunchifymail; // MailSender interface defines a strategy
										// for sending simple mails

	public void crunchifyReadyToSendEmail(String toAddress, String fromAddress, String subject, String msgBody) {

		SimpleMailMessage crunchifyMsg = new SimpleMailMessage();
		crunchifyMsg.setFrom(fromAddress);
		crunchifyMsg.setTo(toAddress);
		crunchifyMsg.setSubject(subject);
		crunchifyMsg.setText(msgBody);
		crunchifymail.send(crunchifyMsg);
	}
}

Step-5

Create Test class CrunchifyEmailTest.java under src/main/java folder.

package crunchify.com.tutorials;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author crunchify.com
 * 
 */

public class CrunchifyEmailTest {

	@SuppressWarnings("resource")
	public static void main(String args[]) {

		// Spring Bean file you specified in /src/main/resources folder
		String crunchifyConfFile = "crunchify-bean.xml";
		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(crunchifyConfFile);

		// @Service("crunchifyEmail") <-- same annotation you specified in CrunchifyEmailAPI.java
		CrunchifyEmailAPI crunchifyEmailAPI = (CrunchifyEmailAPI) context.getBean("crunchifyEmail");
		String toAddr = "test@crunchify.com";
		String fromAddr = "test@crunchify.com";

		// email subject
		String subject = "Hey.. This email sent by Crunchify's Spring MVC Tutorial";

		// email body
		String body = "There you go.. You got an email.. Let's understand details on how Spring MVC works -- By Crunchify Admin";
		crunchifyEmailAPI.crunchifyReadyToSendEmail(toAddr, fromAddr, subject, body);
	}
}

Please make sure you update toAddr and fromAddr above.

Step-6

Now let's run your CrunchifyEmailTest.java and checkout console result. Also don’t forgot to checkout your Gmail.

From my Gmail account:

Email sent by Spring MVC 4.1.6 framework

Console Output:

Jun 22, 2015 8:38:05 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5010be6: startup date [Mon Jun 22 20:38:05 CDT 2015]; root of context hierarchy
Jun 22, 2015 8:38:06 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [crunchify-bean.xml]
DEBUG: JavaMail version 1.4.7
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP gc7sm11710775obb.26 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO 192.168.0.3
250-mx.google.com at your service, [25.15.21.112]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO 192.161.0.22
250-mx.google.com at your service, [25.15.21.112]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN XOAUTH"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM 
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<test@crunchify.com>
250 2.1.0 OK gc7sm11710775obb.26 - gsmtp
RCPT TO:<test@crunchify.com>
250 2.1.5 OK gc7sm11710775obb.26 - gsmtp
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   test@crunchify.com
DATA
354  Go ahead gc7sm11710775obb.26 - gsmtp
Date: Mon, 22 Jun 2015 20:38:08 -0500 (CDT)
From: test@crunchify.com
To: test@crunchify.com
Message-ID: <428566321.0.1435023488148.JavaMail.app@LM-AUN-11000370>
Subject: Hey.. This email sent by Crunchify's Spring MVC Tutorial
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

There you go.. You got an email.. Let's understand details on how Spring MVC works -- By Crunchify Admin
.
250 2.0.0 OK 1435023491 gc7sm11710775obb.26 - gsmtp
QUIT
221 2.0.0 closing connection gc7sm11710775obb.26 - gsmtp

18 thoughts on “Simple way to Send an Email using Spring MVC 5.x.x Framework – org.springframework.mail. javamail.JavaMailSenderImpl”

  1. hello can you help me please. I follow all the steps but still not sending email.
    no error on console log. thank you
    I have this print:
    EHLO dembas-mbp.home
    250-smtp.gmail.com at your service, [95.94.240.46]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250-ENHANCEDSTATUSCODES
    250-PIPELINING
    250-CHUNKING
    250 SMTPUTF8
    DEBUG SMTP: Found extension “SIZE”, arg “35882577”
    DEBUG SMTP: Found extension “8BITMIME”, arg “”
    DEBUG SMTP: Found extension “STARTTLS”, arg “”
    DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
    DEBUG SMTP: Found extension “PIPELINING”, arg “”
    DEBUG SMTP: Found extension “CHUNKING”, arg “”
    DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
    STARTTLS
    220 2.0.0 Ready to start TLS

    Reply
  2. Hi,
    Getting below error while running the code,can you please check once.I have tried changing the spring version but it didn’t work.

    
    Exception in thread "main" org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
      nested exception is:
    	java.net.ConnectException: Connection timed out: connect. Failed messages: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
      nested exception is:
    	java.net.ConnectException: Connection timed out: connect; message exception details (1) are:
    Failed message 1:
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
      nested exception is:
    	java.net.ConnectException: Connection timed out: connect
    	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
    	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    	at javax.mail.Service.connect(Service.java:295)
    	at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
    	at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:421)
    	at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:307)
    	at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:296)
    	at crunchify.com.tutorials.CrunchifyEmailAPI.crunchifyReadyToSendEmail(CrunchifyEmailAPI.java:28)
    	at crunchify.com.tutorials.CrunchifyEmailTest.main(CrunchifyEmailTest.java:30)
    Caused by: java.net.ConnectException: Connection timed out: connect
    	at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    	at java.net.Socket.connect(Socket.java:579)
    	at java.net.Socket.connect(Socket.java:528)
    	at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
    	at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
    	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    	... 8 more

    Thanks in advance.

    Reply
    • Hi Mounika. This looks like a connection timeout error. Make sure you your Eclipse has access to your internet.

      How to verify: When you run program in DEBUG mode it will ask you to allow connection. YES or NO button. Try YES and you shouldn’t see this exception.

      Reply
  3. hi,
    i am getting error while running the application .

    Caused by: java.net.UnknownHostException: smtp.gmail.com
    	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
    	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    
    Exception in thread "main" org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
      nested exception is:
    	java.net.UnknownHostException: smtp.gmail.com. Failed messages: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
      nested exception is:
    	java.net.UnknownHostException: smtp.gmail.com; message exception details (1) are:
    Failed message 1:
    javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
      nested exception is:
    Reply
    • Hi Pradip – are you running code on MAC book? Seems like an issue with host files value.

      Make sure you see values like this:

      ##
      # Host Database
      #
      # localhost is used to configure the loopback interface
      # when the system is booting.  Do not change this entry.
      ##
      127.0.0.1       localhost
      127.0.0.1       appshah-laptop
      
      Reply
  4. I am trying to run this on spring web mvc project on eclipse. I’m getting following message. Do you know what is causing this? Thanks.

    SEVERE: Servlet.service() for servlet [main] in context with path [/spring] threw exception [Request processing failed; nested exception is org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS;
      nested exception is:
        javax.net.ssl.SSLKeyException: RSA premaster secret error. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS;
      nested exception is:
        javax.net.ssl.SSLKeyException: RSA premaster secret error; message exceptions (1) are:
    Failed message 1: javax.mail.MessagingException: Could not convert socket to TLS;
    Reply
    • Hi John – Seems like an error connecting application to gmail server. If you have setup 2 factor authentication then try adding your application specific password.

      Reply

Leave a Comment