JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Send E-mail with attachment using spring 3


This page gives step by step instructions to send email with attachement 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, you can see the code to add attachment:

package com.java2novice.services;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service("emailService")
public class EmailService {

	@Autowired
	private JavaMailSender mailSender;
	
	public void sendEmail(String to,String from,String sub,String msgBody,byte[] content){
		
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(from);
			helper.setTo(to);
			helper.setSubject(sub);
			helper.setText(msgBody);
			helper.addAttachment("MyTestFile.txt", new ByteArrayResource(content));
			mailSender.send(message);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

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 java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

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[]){

		InputStream is = null;
		String toAddr = "[email protected]";
		String fromAddr = "[email protected]";
		String subject = "My Test Mail";
		String body = "Test mail body";
		StringBuilder sb = new StringBuilder();
		String confFile = "applicationContext.xml";
		ConfigurableApplicationContext context 
						= new ClassPathXmlApplicationContext(confFile);
		EmailService emailService = (EmailService) context.getBean("emailService");
		try {
			is = new FileInputStream(new File("/Users/ngootooru/test.txt"));
			byte[] tmp = new byte[4*1024];
			int size = 0;
			while((size = is.read(tmp)) != -1){
				sb.append(new String(tmp, 0, size));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		emailService.sendEmail(toAddr, fromAddr, subject, body, sb.toString().getBytes());
	}
}

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

EHLO 192.168.1.2
250-mx.google.com at your service, [122.166.88.121]
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.2
250-mx.google.com at your service, [122.166.88.121]
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 fk13sm7733236pdb.39 - gsmtp
RCPT TO:<[email protected]>
250 2.1.5 OK fk13sm7733236pdb.39 - gsmtp
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   [email protected]
DATA
354  Go ahead fk13sm7733236pdb.39 - gsmtp
Date: Fri, 18 Jul 2014 20:14:14 +0530 (GMT+05:30)
From: [email protected]
To: [email protected]
Message-ID: <[email protected]>
Subject: My Test Mail
MIME-Version: 1.0
Content-Type: multipart/mixed; 
	boundary="----=_Part_0_994682772.1405694649843"

------=_Part_0_994682772.1405694649843
Content-Type: multipart/related; 
	boundary="----=_Part_1_689477006.1405694649854"

------=_Part_1_689477006.1405694649854
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Test mail body
------=_Part_1_689477006.1405694649854--

------=_Part_0_994682772.1405694649843
Content-Type: text/plain; charset=us-ascii; name=MyTestFile.txt
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename=MyTestFile.txt

r620dev02.corplab.intuit.net
r620sdt01.corplab.intuit.net

------=_Part_0_994682772.1405694649843--
.
250 2.0.0 OK 1405694657 fk13sm7733236pdb.39 - gsmtp
QUIT
221 2.0.0 closing connection fk13sm7733236pdb.39 - gsmtp
<< Previous Program | Next Program >>
blog comments powered by Disqus

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
ServletOuptputStream Vs PrintWriter
ServletOutputStream: ServletResponse.getOutputStream() returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data, it sends the raw data as it is.

PrintWriter: ServletResponse.getWriter() returns PrintWriter object which sends character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified then it does default character encoding.
Famous Quotations
Never argue with a fool, onlookers may not be able to tell the difference.
-- Mark Twain

About Author

Most Visited Pages

Other Interesting Sites

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