How to send Email in Java using Spring - JavaMailSenderImple Example

Email is an essential function of any enterprise Java application. Your application will need Email functionality to send reminders, bills, payments, confirmations, passwords, alerts, and several other kinds of system notifications. There is hardly any enterprise application in Java which doesn't send emails. It could be for a functional reason or non-functional reason but you will find yourself writing code to send emails every now and then, but it's not straight forward in Java. You need to include Java Mail API and learn some key classes and how to configure them to send emails from Java Programs. You can see the whole process in my earlier article about how to send emails from Java Program, but the point is that its not so easy.

Fortunately, Spring's JavaMailSenderImpl makes sending emails from Java ridiculously easy.
It's a production implementation of JavaMailSender interface and supports both SimpleMailMessage from Spring, and MimeMessages from JavaMail API.

The good thing about this class is that it allows you to define mail settings as bean properties as well as using a pre-configured JavaMail Session, which can be obtained from an application server's JNDI environment.

I am expecting that you already know Spring framework, at least you are familiar with writing Spring configuration file and declaring Spring beans using XML or configuring them using Java and Annotation configuration method, but, if you are not then I suggest you to first go through a comprehensive Spring online course like Spring Framework 5: Beginner to Guru on Udemy to learn basics.

How to send Email in Java using Spring - JavaMailSenderImple Example


This is one of the most up-to-date courses where you will learn everything about the Spring framework from scratch by one of the best Spring instructors on Udemy, John Thomson.  It also covers the latest Spring 5 features like Reactive Programming and WebFlux.




How to send Mail in Java using Spring Framework

Here is your step by step guide to sending email from a Java application using Spring Framework and its utility classes like JavaMailSenderImpl another template class which takes away most of the pain associated with sending emails using Java mail API



Step 1: Configure JavaMailSenderImpl as Spring bean in ApplicationContext.xml


<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="25"/>
    <property name="username" value="#emailid"/>       
    <property name="password" value="#password"/>

    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtps.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.smtp.ssl.enable">false</prop>
            <prop key="mail.debug">true</prop>
        </props>
    </property>
</bean>


Step 2: Configure our test application with JavaMailSenderImpl reference.


<bean id="javaApp" class="com.javarevisited.demo.SpringEmailDemo">
    <property name="mailSender" ref="mailSender"/>
</bean>

Step 3: Create our Java application to send Email


package com.javarevisited.demo;

public class SpringEmailDemo {
    private JavaMailSender mailSender;
    //setter getters

    public MimeMessage getMailMessage() throws MessagingException {
        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false);
        helper.setFrom("javarevisited@gmail.com");
        helper.setTo("abc@gmail.com");
        helper.setCc("def@gmail.com");
        helper.setBcc("fgh@gmail.com");
        helper.setSubject("How are you doing?");
        helper.setText("This is a test mail",true);
        return mimeMessage;
    }

    public void sendMail() throws MailException, MessagingException {
        mailSender.send(getMailMessage());
    }
}


That's all about how to send emails from Java using the Spring framework. This is a concise example, but Spring is mighty for sending all kinds of emails like email with an attachment, an email with HTML content, an email with images, and so on. If you want to learn more about those features, I suggest you join a comprehensive Spring framework course like  Spring Framework 5: Beginner to Guru, which will teach you everything about Spring Framework.


Further Learning
Spring in Action 5th Edition (Book)
Spring Master Class - Beginner to Expert
Introduction to Spring MVC 4 By Bryan Hansen


Other Java and Spring articles you may like
  • 5 Spring Boot Features Every Java Developer Should Know (features)
  • The 2019 Java Developer RoadMap (roadmap)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • 15 Spring Boot Interview Questions for Java Programmers (questions)
  • 10 Tips to become a better Java developer in 2019 (tips)
  • 3 Best Practices Java Programmers can learn from Spring (best practices)
  • 5 courses to learn Spring Boot and Spring Cloud in 2019( courses)
  • 3 ways to change Tomcat port in Spring Boot (tutorial)
  • Top 5 Free Courses to learn Spring and Spring Boot in 2019 (courses)
  • 5 Course to Master Spring Boot online in 2019 (courses)
  • 10 Things Java Developer should learn in 2019 (goals)
  • 10 Spring MVC annotations Java developers should learn (annotations)
  • 10 Spring Core Annotations Java Developers should learn (annotations)

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you want to learn Spring and looking for a free online course then you can also check out the Spring Core - Learn Spring Framework 4 and Spring Boot on Udemy, it's completely free and all you need to do is create an account to enroll into this course.

No comments:

Post a Comment