Backend Development 11 min read

Spring Boot Email Integration: JavaMailSender, JavaMail API, and Apache Commons Email with Code Samples

This tutorial explains three approaches to sending email in Spring Boot—JavaMailSender, JavaMail API, and Apache Commons Email—compares their advantages and disadvantages, and provides complete Maven dependencies, configuration settings, and ready‑to‑run code examples for each method.

Wukong Talks Architecture
Wukong Talks Architecture
Wukong Talks Architecture
Spring Boot Email Integration: JavaMailSender, JavaMail API, and Apache Commons Email with Code Samples

Background : The author introduces a series called "SpringBoot Email Upgrade" that aims to guide developers from zero to building a complete email service using the SpringBoot technology stack.

Three ways to send email in SpringBoot :

JavaMailSender provided by Spring Framework (high integration, recommended).

JavaMail API (flexible, supports advanced scenarios such as calendar reminders).

Apache Commons Email library (simple API).

Choosing a solution : If the project already uses Spring and only basic email sending is needed, JavaMailSender is convenient; for higher control or special scenarios, use JavaMail API; for a balance between simplicity and flexibility, consider Apache Commons Email.

Comparison of pros and cons :

1. JavaMailSender (Spring Framework)

Advantages

High integration with Spring.

Simple configuration thanks to Spring Boot auto‑configuration.

Simplified API makes code clear and concise.

Disadvantages

Lower flexibility for advanced requirements.

Brings a relatively large dependency if only email is needed.

2. JavaMail API

Advantages

High flexibility and low‑level control.

Standard Java library with good portability.

Disadvantages

More verbose code; higher learning curve for beginners.

3. Apache Commons Email

Advantages

Simplified API, easier to send HTML or other email types.

Reduces boilerplate code.

Disadvantages

Less flexible than raw JavaMail API.

Introduces an additional external dependency.

JavaMailSender example :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    public void sendEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private EmailService emailService;

    @GetMapping("/send")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
        emailService.sendEmail(to, subject, text);
        return "Email sent successfully!";
    }
}

Configure SMTP settings in application.properties or application.yml (host, username, password, port, protocol, SSL, etc.).

JavaMail API example :

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Service
public class EmailService {
    @Value("${spring.mail.username}")
    private String from;

    public void sendSimpleEmail(String to, String subject, String text) throws MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "your_smtp_host");
        props.put("mail.smtp.port", "your_smtp_port");
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "your_email_password");
            }
        });
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(text);
        Transport.send(message);
    }
}
@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private EmailService emailService;

    @GetMapping("/send")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
        try {
            emailService.sendSimpleEmail(to, subject, text);
            return "Email sent successfully!";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "Failed to send email.";
        }
    }
}

Apache Commons Email example :

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-email</artifactId>
    <version>1.5</version>
</dependency>
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class EmailService {
    @Value("${spring.mail.username}")
    private String from;

    public void sendSimpleEmail(String to, String subject, String text) throws EmailException {
        SimpleEmail email = new SimpleEmail();
        email.setHostName("your_smtp_host");
        email.setSmtpPort(Integer.parseInt("your_smtp_port"));
        email.setAuthenticator(new DefaultAuthenticator(from, "your_email_password"));
        email.setStartTLSEnabled(true);
        email.setFrom(from);
        email.addTo(to);
        email.setSubject(subject);
        email.setMsg(text);
        email.send();
    }
}
@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private EmailService emailService;

    @GetMapping("/send")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
        try {
            emailService.sendSimpleEmail(to, subject, text);
            return "Email sent successfully!";
        } catch (EmailException e) {
            e.printStackTrace();
            return "Failed to send email.";
        }
    }
}

All three methods can be tested with Swagger, Postman, or similar tools. The article also includes QR codes for joining the author's knowledge community and obtaining the full project code.

backendSpringBoottutorialemailApache Commons EmailjavamailJavaMailSender
Wukong Talks Architecture
Written by

Wukong Talks Architecture

Explaining distributed systems and architecture through stories. Author of the "JVM Performance Tuning in Practice" column, open-source author of "Spring Cloud in Practice PassJava", and independently developed a PMP practice quiz mini-program.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.