This tutorial will show you how to send a basic mail via Spring framework’s email support.

The Spring Framework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client. A class that comes in pretty handy when dealing with JavaMail messages is the org.springframework.mail.javamail.MimeMessageHelper class, which shields you from having to use the verbose JavaMail API. Using the MimeMessageHelper it is pretty easy to create a MimeMessage. Multipart email messages allow for both attachments and inline resources. The following example shows you how to use the MimeMessageHelper to send an email along with a single MS Word attachment.
For this tutorial we will create a standalone maven project in Eclipse. If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

Prerequisites

The following configurations are required in order to run the application

Eclipse Mars
JDK 1.8
Have maven installed and configured
Spring and Java Mail dependencies in pom.xml

Now we will see the below steps how to create a maven based spring project in Eclipse

Step 1. Create a standalone maven project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-quickstart

Now enter the required fields (Group Id, Artifact Id) as shown below

Group Id : com.roytuts
Artifact Id : springcore

Step 2. Modify the pom.xml file as shown below.

<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.roytuts</groupId>
    <artifactId>springcore</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springcore</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jdk.version>1.8</jdk.version>
        <junit.version>4.11</junit.version>
        <java.mail.version>1.4.7</java.mail.version>
        <spring.version>4.2.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- Spring framework -->
        <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>

        <!-- Java Mail API -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>${java.mail.version}</version>
        </dependency>

        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Step 4. Create src/main/resources folder for putting the resource files.

Do right-click on the project and go New -> Source Folder. Give Folder name: as src/main/resources and click on Finish button.

Step 5. Create an XML file email.xml under src/main/resources.

Do right-click on src/main/resources in the project and go New -> file. Give File name: as email.xml and click on Finish button.

<?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:p="http://www.springframework.org/schema/p"
    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">

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.roytuts.com" />
        <property name="port" value="121" />
        <property name="username" value="contact@roytuts.com" />
        <property name="password" value="******" />
        <property name="javaMailProperties">
            <props>
                <!-- if you need ssl then uncomment below two lines -->
                <!-- <prop key="mail.smtp.ssl.trust">smtp.roytuts.com</prop>
                <prop key="mail.smtp.starttls.enable">true</prop> -->
                <prop key="mail.smtp.auth">true</prop>
            </props>
        </property>
    </bean>

    <bean id="emailSender" class="com.roytuts.springcore.email.EmailSender">
        <property name="mailSender" ref="mailSender" />
    </bean>
</beans>

Step 6. Create below EmailSender class under src/main/java folder

package com.roytuts.springcore.email;

import java.io.File;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class EmailSender {

    @Autowired
    private JavaMailSender mailSender;

    public void sendEmailAttachment(final String subject, final String message, final String emailAddress,
            final File attachment, final boolean isHtmlMail) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            // use the true flag to indicate you need a multipart message
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom("contact@roytuts.com");
            helper.setTo(emailAddress);
            helper.setSubject(subject);
            if (isHtmlMail) {
                helper.setText("<html><body>" + message + "</html></body>", true);
            } else {
                helper.setText(message);
            }
            //add the file attachment
            FileSystemResource file = new FileSystemResource(attachment);
            helper.addAttachment(attachment.getName(), file);
            mailSender.send(mimeMessage);
            System.out.println("Email sending complete.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public JavaMailSender getMailSender() {
        return mailSender;
    }
    
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

}

Step 7. Create below Junit test class under src/test/java folder to test the application

package com.roytuts.springcore.email;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmailSenderTest {

    private EmailSender emailSender;

    @Before
    public void setUp() throws Exception {
        @SuppressWarnings("resource")
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("email.xml");
        emailSender = applicationContext.getBean("emailSender", EmailSender.class);
    }

    @Test
    public void testSendEmail() {
        File attachment = new File("D:/JavaJ2EE_Soumitra-Sarkar.doc");
        emailSender.sendEmailAttachment("How are you ?",
                "Hello Dear, <i>How are you ?</i> <br/> Please open the attachment", "soumitrajuster@gmail.com",
                attachment, true);
    }

}

Step 8. Now run the above Junit test class, you will see the below output in console

Console Output

Apr 23, 2016 8:51:19 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@265ba4: startup date [Fri Apr 23 08:51:19 IST 2016]; root of context hierarchy
Apr 23, 2016 8:51:19 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [email.xml]
Email sending complete.

Step 9. Check the inbox you will get a message. If you do not find the message in inbox then check the Spam folder.
email spring attachment

See in the above image how <i/>, <br/> tags made italic & break in HTML email.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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