Integrating Mailgun with Spring Boot 3 to Send Emails Efficiently

What is Mailgun

Mailgun is a powerful email service provider that allows developers to send, receive, and track emails very efficiently with any extra efforts. It provides a robust API and SMTP relay for sending transactional and marketing emails. In this blog, we will explore how to integrate Mailgun with a Spring Boot application and send emails efficiently. Let’s integrate mailgun with spring boot step by step.

mailgun with spring boot

Table of the content

  • Create and configure a mailgun account
  • Add dependencies to you spring boot application
  • Configure Mailgun in Spring Boot
  • Create a Mail Service Using Mailgun SDK
  • Create a Controller to Send Emails
  • Testing the Integration
  • Enhancing Efficiency
  • Send mail with inline image using mailgun

Prerequisites

Before integrating Mailgun with Spring Boot, ensure you have:

  • A Mailgun account (Sign up at Mailgun)
  • A Spring Boot application
  • Java 11 or later
  • Maven or Gradle for dependency management

Create and configure a mailgun account

  • Sign up for a Mailgun account and get your API key.
  • Verify your domain in the Mailgun dashboard.
  • Note down your API Key and Domain Name as you will need them later.

Add Dependencies to Your Spring Boot Application

Add the following dependencies to your pom.xml if you’re using Maven:


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

<dependency>
    <groupId>com.mailgun</groupId>
    <artifactId>mailgun-java</artifactId>
    <version>1.0.0</version>
</dependency>

For Gradle users, add the dependencies in build.gradle:


dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'com.mailgun:mailgun-java:1.0.0'
}

Configure Mailgun in Spring Boot

In application.properties or application.yml, add the Mailgun SMTP settings:


mailgun.api.key=your-mailgun-api-key
mailgun.domain=your-domain
mailgun.from.email=your-email@example.com

Create a Mail Service Using Mailgun SDK

Create a service to send emails using Mailgun’s official Java SDK:


package com.example.mailgun.service;

import com.mailgun.api.v3.MailgunMessagesApi;
import com.mailgun.client.MailgunClient;
import com.mailgun.model.message.Message;
import com.mailgun.model.message.MessageResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;

@Service
public class MailgunService {

    @Value("${mailgun.api.key}")
    private String apiKey;

    @Value("${mailgun.domain}")
    private String domain;

    @Value("${mailgun.from.email}")
    private String emailFrom;

    public void sendEmail(String to, String subject, String text) {

        try {
        MailgunMessagesApi mailgunMessagesApi = MailgunClient.config(apiKey)
                .createApi(MailgunMessagesApi.class);

        Message message = Message.builder()
                .from(emailFrom)
                .to(to)
                .subject(subject)
                .text(text)
                .build();

        // Send mail asynchronously
        CompletableFuture<MessageResponse> response = mailgunMessagesApi.sendMessageAsync(domain, message);
        log.info("Email sent successfully to: " + emailTo);
        } catch (Exception e) {
            log.error("Failed to send email", e);
            throw new RuntimeException("Failed to send the mail", e);
        }
}

Create a Controller to Send Emails

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/email")
public class EmailController {

    private final MailgunService mailgunService;

    public EmailController(MailgunService mailgunService) {
        this.mailgunService = mailgunService;
    }

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

Testing the Integration

http://localhost:8080/email/send

with parameter

 
{
    "to": "recipient@example.com",
    "subject": "Test Email",
    "text": "Hello from Mailgun!"
}

To send emails efficiently

  • Use background jobs (e.g., Spring Boot’s @Async) to avoid blocking API calls.
  • Monitor delivery logs in the Mailgun dashboard.
  • Use templates for better email formatting.
  • Leverage Mailgun’s tracking features to analyze email engagement.

Send mail with inline image using mailgun

Create the Email Templates

Create an HTML email template inside src/main/resources/templates/email-template.html :


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Email with Logo</title>
    </head>
    <body>
        <div style="text-align: center; font-family: Arial, sans-serif;">
            <img th:src="|cid:logo.png|" alt="Company Logo" width="150"/>
            <h2>This is how we can send the mail with inline image</h2>
        </div>
    </body>
</html>

Sending mail with inline image


public void sendEmailWithInlineImage(String emailTo, String subject, String htmlContent) {
    try {
        // Load the image from classpath
        ClassPathResource logoImage = new ClassPathResource("/static/images/logo.png");
        File tempFile = new File("/tmp/logo.png");

        // Write image to a temp file
        if (!tempFile.exists()) {
            try (InputStream inputStream = logoImage.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        }

        // Create primary message object with inline image
        Message message = Message.builder()
                .from(emailFrom)
                .to(emailTo)
                .subject(subject)
                .html(htmlContent)
                .inline(tempFile) // Attach inline image
                .build();

        // Create Mailgun client and API instance
        MailgunMessagesApi mailgunMessagesApi = MailgunClient.config(apiKey)
                .createApi(MailgunMessagesApi.class);

        // Send mail asynchronously
        CompletableFuture<MessageResponse> response = mailgunMessagesApi.sendMessageAsync(domain, message);
        log.info("Email with inline image sent successfully to: " + emailTo);
    } catch (IOException e) {
        log.error("Failed to send email with inline image", e);
        throw new RuntimeException("Failed to send the mail", e);
    }
}

Conclusion

Mailgun provides a seamless way to send emails in a Spring Boot application using both SMTP and API methods. By following this guide, you can easily integrate Mailgun, send emails efficiently, and optimize your email delivery process.

Explore our more articles

How to Integrate Mailgun with Spring Boot 3

Mailgun is a powerful email service provider that allows developers to send, receive, and track emails very efficiently with any extra efforts. It provides a robust API and SMTP relay for sending transactional and marketing emails. In this blog, we will explore how to integrate Mailgun with a Spring Boot application and send emails efficiently. Let’s integrate mailgun with spring boot step by step.

– Create and configure a mailgun account
– Add dependencies to you spring boot application
– Configure Mailgun in Spring Boot
– Create a Mail Service Using Mailgun SDK
– Create a Controller to Send Emails
– Testing the Integration
– Enhancing Efficiency
– Send mail with inline image using mailgun

How to Send mail with inline image using mailgun

To send an inline image with an email using Mailgun, you need to attach the image to the email as an inline attachment. You can do this by utilizing the Mailgun SDK when creating the message object. The SDK allows you to specify the inline image by setting it as an inline attachment while constructing the email message.

Leave a Comment