JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Send E-mail using spring 3


This page gives step by step instructions to send email using spring 3. This example uses org.springframework.mail.javamail.JavaMailSender interface to send email.

Here is the maven pom.xml file with required dependencies:

<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>SpringJavaBasedConfig</groupId>
	<artifactId>SpringJavaBasedConfig</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<properties>
		<spring.version>3.2.0.RELEASE</spring.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<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>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.7</version>
		</dependency>
	</dependencies>
</project>

Here is the sample code for email sender service:

package com.java2novice.services;

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

@Service("emailService")
public class EmailService {

	@Autowired
	private MailSender mailSender;
	
	public void sendEmail(String to, String from, String sub, String msgBody){
		
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(sub);
		message.setText(msgBody);
		mailSender.send(message);
	}
}

Xml based configuration file with java mail properties:

<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="com.java2novice" /> 
    
    <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="user_name" />
		<property name="password" value="password" />
	 
		<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>

Finally email sender demo class:

package com.java2novice.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.services.EmailService;

public class SpringDemo {

	public static void main(String a[]){

		String confFile = "applicationContext.xml";
		ConfigurableApplicationContext context 
						= new ClassPathXmlApplicationContext(confFile);
		EmailService emailService = (EmailService) context.getBean("emailService");
		String toAddr = "[email protected]";
		String fromAddr = "[email protected]";
		String subject = "My Test Mail";
		String body = "Test mail body";
		emailService.sendEmail(toAddr, fromAddr, subject, body);
	}
}

Output:
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 lq6sm11044811pab.48 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO 192.168.1.4
250-mx.google.com at your service, [122.166.147.61]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250 CHUNKING
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 "CHUNKING", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO 192.168.1.4
250-mx.google.com at your service, [122.166.147.61]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
250-ENHANCEDSTATUSCODES
250 CHUNKING
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "CHUNKING", 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:<[email protected]>
250 2.1.0 OK lq6sm11044811pab.48 - gsmtp
RCPT TO:<[email protected]>
250 2.1.5 OK lq6sm11044811pab.48 - gsmtp
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   [email protected]
DATA
354  Go ahead lq6sm11044811pab.48 - gsmtp
Date: Thu, 17 Jul 2014 20:24:34 +0530 (GMT+05:30)
From: [email protected]
To: [email protected]
Message-ID: <1621366179.0.1405608874431.JavaMail.ngootooru@BANL1191b66dd.local>
Subject: My Test Mail
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Test mail body
.
250 2.0.0 OK 1405608876 lq6sm11044811pab.48 - gsmtp
QUIT
221 2.0.0 closing connection lq6sm11044811pab.48 - gsmtp
<< Previous Program | Next Program >>

Spring framework examples

  1. Spring 3 hello world example
  2. Spring bean java based configuration using @Configuration and @Bean
  3. How to get spring application context object reference?
  4. How to load multiple spring bean configuration files?
  5. Spring java based configuration @Import example
  6. Spring Dependency Injection and Types
  7. Spring Dependency Injection via setter method
  8. Spring Dependency Injection via Constructor
  9. Constructor overloading issue with spring constructor injection
  10. Constructor vs Setter dependency Injection in Spring
  11. How to inject value into spring bean instance variables?
  12. Spring bean tag properties
  13. Differen types of spring bean scopes
  14. How to inject inner bean in spring?
  15. Set spring bean scope using annotation
  16. How to invoke spring bean init and destroy methods?
  17. Spring bean initialization callback
  18. Spring bean destruction callback
  19. Configure default initialization and destroy method in all spring beans
  20. Spring bean init and destroy methods using annotations
  21. Spring Bean Post Processors
  22. How to read property file in spring using xml based configuration file?
  23. How to read property file in spring 3.0 using java based configuration?
  24. How to inject date into spring bean property?
  25. How to inject date into spring bean with CustomDateEditor?
  26. Spring bean inheritance configuration
  27. Spring dependency checking with @Required annotation
  28. How to define a custom Required-style annotation for dependency checking?
  29. How to inject List into spring bean?
  30. How to inject Set into spring bean?
  31. How to inject Map into spring bean?
  32. How to enable auto component scanning in spring?
  33. Difference between @Component, @Service, @Repository and @Controller
  34. How to filter components in auto scanning?
  35. Spring expression language basic example using xml based configuration.
  36. Spring expression language basic example using annotations.
  37. Bean reference example using spring expression language
  38. Spring expression language operators example
  39. Spring expression language ternary operator example
  40. How to use regular expressions with spring expression language?
  41. How to use collections with spring expression language?
  42. Spring bean auto-wiring modes
  43. Spring auto-wiring mode byName
  44. Spring auto-wiring mode byType
  45. Spring auto-wiring mode constructor
  46. Spring auto-wiring using @Autowired annotation example
  47. Spring auto-wiring using @Qualifier annotation example
  48. Spring log4j configuration
  49. How to schedule jobs using @Scheduled annotation in spring?
  50. Send E-mail using spring 3
  51. Send E-mail with attachment using spring 3
  52. Simple spring JDBC example
  53. Spring JDBC example with JdbcTemplate
  54. Spring JDBC example with JdbcDaoSupport
  55. Spring JDBC query example using JdbcDaoSupport
  56. How to query single column using spring JdbcTemplate?
  57. Spring JDBC batch updates using JdbcTemplate?
  58. Spring AOP Advices - Before advice example - xml based configuration
  59. Spring AOP Advices - After returning advice example - xml based configuration
  60. Spring AOP Advices - After throwing advice example - xml based configuration
  61. Spring AOP Advices - Around advice example - xml based configuration
  62. Spring AOP Advice - Pointcuts – Name match example
  63. Spring AOP Advice - Pointcuts – Regular expression example
  64. Spring AOP - AspectJ - @Before example
  65. Spring AOP - AspectJ - @After example
  66. Spring AOP - AspectJ - @AfterReturning example
  67. Spring AOP - AspectJ - @AfterThrowing example
  68. Spring AOP - AspectJ - @Around example
Knowledge Centre
What is transient variable?
Transient variables cannot be serialized. During serialization process, transient variable states will not be serialized. State of the value will be always defaulted after deserialization.
Famous Quotations
The pessimist complains about the wind; the optimist expects it to change; the realist adjusts the sails.
-- William Arthur Ward

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.