Flat Preloader Icon

Spring Java Mail

Sending emails in a Spring application can be achieved using the Spring Framework’s integration with JavaMail. Below, I’ll provide a step-by-step tutorial on how to send emails in a Spring application using JavaMail.
Step 1: Set Up Your Spring Project

Create a new Spring project or use an existing one. Ensure that you have the necessary Spring and JavaMail dependencies in your project’s build file (e.g., Maven or Gradle). Here’s an example of Maven dependencies:
				
					<dependencies>
    <!-- Spring dependencies -->
    <dependency>
        <groupId>org
        .springframework</groupId>
        <artifactId>spring-context
        </artifactId>
        <version>5.3.10.RELEASE</version>
    </dependency>

    <!-- JavaMail dependencies -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>
            javax.mail-api</artifactId>
        <version>1.6.2</version>
    </dependency>
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>
            javax.mail</artifactId>
        <version>1.6.2</version>
    </dependency>
</dependencies>

				
			
Step 2: Configure Email Properties

Create a Spring configuration file (e.g., spring-mail-config.xml) and configure your email properties. You’ll need to specify the mail server details, username, and password. Below is an example of a simple configuration:
				
					<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"
xmlns:
util="http://www.springframework
.org/schema/util"
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
http://www.springframework.org/schema/util
http://www.springframework.org
/schema/util/spring-util.xsd">

    <!-- Enable Spring's property placeholder
    for externalizing configuration -->
    <context:property-placeholder 
    location="classpath:email.properties" />

    <!-- JavaMail Sender -->
    <bean id="mailSender" class
    ="org.springframework.mail.
    javamail.JavaMailSenderImpl">
        <property name="host"
        value="${mail.host}" />
        <property name="port" 
        value="${mail.port}" />
        <property name="username" 
        value="${mail.username}" />
        <property name="password" 
        value="${mail.password}" />
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">
                    ${mail.smtp.auth}</prop>
    <prop key="mail.smtp.starttls.enable">
        ${mail.smtp.starttls.enable}</prop>
            </props>
        </property>
    </bean>
</beans>

				
			

In the above configuration, we’re using a property file (email.properties) to externalize sensitive information like the email server credentials. Create this property file and specify the required properties.

Step 3: Create a Service to Send Emails

Create a service class that will send emails. Here’s an example of a simple email service:Create a service class that will send emails. Here’s an example of a simple email service:
				
					import org.springframework.mail
.SimpleMailMessage;
import org.springframework.mail.javamail
.JavaMailSender;
import org.springframework
.stereotype.Service;

@Service
public class EmailService {

    private final JavaMailSender mailSender;

    public EmailService
    (JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendEmail(String to,
    String subject,String text) {
        SimpleMailMessage message
        = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
    }
}

				
			

In the above configuration, we’re using a property file (email.properties) to externalize sensitive information like the email server credentials. Create this property file and specify the required properties.

Step 4: Use the Email Service

You can now use the EmailService in your application to send emails. For example, in a controller or another service:
				
					import org.springframework
.stereotype.Controller;
import org.springframework.web.bind
.annotation.RequestMapping;

@Controller
public class EmailController {

    private final EmailService emailService;

    public EmailController(EmailService
    emailService) 
    {
        this.emailService = emailService;
    }

    @RequestMapping("/sendEmail")
    public String sendEmail() {
        String to = "recipient@example.com";
        String subject 
        = "Hello from Spring Email";
        String text = 
        "This is a test email sent from 
        a Spring application.";

        emailService.sendEmail
        (to, subject, text);

        return "Email sent successfully!";
    }
}

				
			
Step 5: Run Your Spring Application

Run your Spring application, and when you access the /sendEmail endpoint, it will send the email using the configured JavaMailSender.

Make sure to replace the placeholders like ${mail.host}, ${mail.port}, ${mail.username}, and ${mail.password} with your actual email server configuration in the email.properties file.

This is a basic example of sending emails with Spring and JavaMail. Depending on your requirements, you can enhance this by handling email templates, attachments, and more.

Share on: