Sending email

suggest change

In the Java ecosystem, sending emails is primarily achieved using Jakarta Mail (formerly JavaMail / javax.mail) or through the higher-level JavaMailSender abstraction provided by Spring Boot.


1. Sending Plain-Text Email with Jakarta Mail

The Jakarta Mail specification defines standard interfaces for composing and dispatching messages over SMTP. In modern Java (Java 11+ and Jakarta EE), the reference implementation is Eclipse Angus Mail.

Maven Dependencies

<dependency>
    <groupId>jakarta.mail</groupId>
    <artifactId>jakarta.mail-api</artifactId>
    <version>2.1.5</version>
</dependency>
<dependency>
    <groupId>org.eclipse.angus</groupId>
    <artifactId>angus-mail</artifactId>
    <version>2.0.5</version>
    <scope>runtime</scope>
</dependency>

Complete SMTP STARTTLS Example

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

public class EmailSender {

    public static void sendSimpleMessage(String to, String subject, String bodyText) throws MessagingException {
        final String smtpHost = "smtp.gmail.com";
        final String smtpPort = "587"; // STARTTLS port
        final String username = System.getenv("SMTP_USERNAME");
        final String password = System.getenv("SMTP_PASSWORD"); // Use App Password

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");
        props.put("mail.smtp.ssl.protocols", "TLSv1.2 TLSv1.3");

        // Authenticate with the mail server
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // Compose the message
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(bodyText);

        // Dispatch over network
        Transport.send(message);
        System.out.println("Email successfully dispatched to " + to);
    }
}

2. Sending HTML Emails with File Attachments

To combine HTML bodies with file attachments, compose a MimeMultipart structure:

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;

import java.io.File;
import java.io.IOException;

public class RichEmailSender {

    public static void sendHtmlEmailWithAttachment(Session session, String from, String to, 
                                                   String subject, String htmlContent, 
                                                   File attachment) throws MessagingException, IOException {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);

        // Multipart container
        Multipart multipart = new MimeMultipart();

        // 1. HTML Body Part
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlContent, "text/html; charset=UTF-8");
        multipart.addBodyPart(htmlPart);

        // 2. Attachment Part
        if (attachment != null && attachment.exists()) {
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.attachFile(attachment);
            multipart.addBodyPart(attachmentPart);
        }

        // Attach the multipart payload to the message
        message.setContent(multipart);

        Transport.send(message);
    }
}

3. Sending Email in Spring Boot with JavaMailSender

Spring Boot simplifies email delivery by auto-configuring JavaMailSender from application.properties.

1. Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. Configuration (application.properties)

spring.mail.host=smtp.sendgrid.net
spring.mail.port=587
spring.mail.username=apikey
spring.mail.password=${SENDGRID_API_KEY}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

3. Service Implementation

package com.example.service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
public class EmailNotificationService {

    private final JavaMailSender mailSender;

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

    // Run asynchronously to avoid blocking the user's web request
    @Async
    public void sendOrderConfirmation(String recipientEmail, String orderId, File invoicePdf) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            // true flag indicates multipart (for HTML and attachments)
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom("orders@mystore.com");
            helper.setTo(recipientEmail);
            helper.setSubject("Your Order #" + orderId + " is Confirmed");
            helper.setText("<h1>Thank you for your order!</h1><p>Please find your invoice attached.</p>", true);

            if (invoicePdf != null && invoicePdf.exists()) {
                helper.addAttachment("invoice-" + orderId + ".pdf", new FileSystemResource(invoicePdf));
            }

            mailSender.send(message);
        } catch (MessagingException e) {
            // Log error or push to a dead-letter queue for retry
            System.err.println("Failed to send order email: " + e.getMessage());
        }
    }
}

4. Asynchronous Sending with CompletableFuture

Network latency to external SMTP servers can take hundreds of milliseconds to several seconds. In non-Spring applications, dispatch emails on background threads using CompletableFuture:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncEmailDispatcher {

    private static final ExecutorService emailExecutor = Executors.newFixedThreadPool(4);

    public static CompletableFuture<Void> dispatchAsync(String to, String subject, String body) {
        return CompletableFuture.runAsync(() -> {
            try {
                EmailSender.sendSimpleMessage(to, subject, body);
            } catch (Exception ex) {
                System.err.println("Async email failed: " + ex.getMessage());
            }
        }, emailExecutor);
    }
}

5. Security and Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents