Send Emails with Amazon SES from the Micronaut Framework

Learn how to send emails with Amazon SES from a Micronaut application

Authors: Sergio del Amo

Micronaut Version: 4.3.7

1. Getting Started

In this guide, we will create a Micronaut application written in Kotlin.

2. What you will need

To complete this guide, you will need the following:

3. Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

4. Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=graalvm,email-amazon-ses,aws-v2-sdk,validation,yaml,reactor \
    --build=gradle \
    --lang=kotlin \
    --test=junit
If you don’t specify the --build argument, Gradle is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add graalvm, email-amazon-ses, aws-v2-sdk, validation, yaml, and reactor features.

If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features and apply those changes to your application.

4.1. Controller

Create a MailController class. This class uses a collaborator, emailSender, to send an email.

You can send emails asynchronously using the AysnEmailSender API or synchronously using the EmailSender API.

src/main/kotlin/example/micronaut/MailController.kt
package example.micronaut

import io.micronaut.email.AsyncEmailSender
import io.micronaut.email.BodyType.HTML
import io.micronaut.email.Email
import io.micronaut.email.EmailException
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus.UNPROCESSABLE_ENTITY
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Post
import io.micronaut.http.exceptions.HttpStatusException
import org.reactivestreams.Publisher
import org.slf4j.LoggerFactory
import reactor.core.publisher.Mono
import software.amazon.awssdk.services.ses.model.SendEmailResponse
import software.amazon.awssdk.services.ses.model.SesRequest
import software.amazon.awssdk.services.ses.model.SesResponse

@Controller("/mail") (1)
class MailController(private val emailSender: AsyncEmailSender<SesRequest, SesResponse>) { (2)

    @Post("/send") (3)
    fun send(@Body("to") to: String): Publisher<HttpResponse<*>> { (4)
        return Mono.from(emailSender.sendAsync(Email.builder()
                .to(to)
                .subject("Sending email with Amazon SES is Fun")
                .body("and <em>easy</em> to do anywhere with <strong>Micronaut Email</strong>", HTML)))
                .doOnNext { rsp: SesResponse? ->
                    if (rsp is SendEmailResponse) {
                        LOG.info("message id: {}", rsp.messageId())
                    }
                }.onErrorMap(EmailException::class.java) { t: EmailException? -> HttpStatusException(UNPROCESSABLE_ENTITY, "Email could not be sent") }
                .map { rsp: SesResponse? -> HttpResponse.accepted<Any?>() } (5)
    }

    companion object {
        private val LOG = LoggerFactory.getLogger(MailController::class.java)
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /mail/send.
2 Use constructor injection to inject a bean of type AsyncEmailSender.
3 The @Post annotation maps the send method to an HTTP POST request on /mail/send.
4 You can use a qualifier within the HTTP request body. For example, you can use a reference to a nested JSON attribute.
5 Return 202 ACCEPTED as the result if the email delivery succeeds

4.2. Configuration

If you want to send every email with the same address, you can set it via configuration:

src/main/resources/application.yml
---
micronaut:
  email:
    from:
      email: 'john@micronaut.example'

This is possible thanks to Email Decorators.

4.3. AWS SES

Amazon Simple Email Service (Amazon SES) is a cloud-based email-sending service designed to help digital marketers and application developers send marketing, notification, and transactional emails. It is a reliable, cost-effective service for businesses of all sizes that use email to keep in contact with their customers.

4.3.1. Dependency

Because we added the email-amazon-ses feature, the application contains the following dependency:

build.gradle
implementation("com.micronaut.email:micronaut-email-amazon-ses")

4.4. Micronaut AWS SDK v2

Micronaut Amazon SES integration uses Micronaut AWS SDK v2 integration.

Because we added the aws-v2-sdk feature, the application contains the following dependency:

build.gradle
implementation("io.micronaut.aws:micronaut-aws-sdk-v2")

Read about:

4.5. Test

Create a test bean that replaces the bean of type AsyncTransactionalEmailSender.

src/test/kotlin/example/micronaut/EmailSenderReplacement.kt
package example.micronaut

import io.micronaut.context.annotation.Replaces
import io.micronaut.context.annotation.Requires
import io.micronaut.email.AsyncTransactionalEmailSender
import io.micronaut.email.Email
import io.micronaut.email.EmailException
import io.micronaut.email.ses.AsyncSesEmailSender
import jakarta.inject.Named
import jakarta.inject.Singleton
import org.reactivestreams.Publisher
import reactor.core.publisher.Mono
import software.amazon.awssdk.services.ses.model.SendEmailResponse
import software.amazon.awssdk.services.ses.model.SesRequest
import software.amazon.awssdk.services.ses.model.SesResponse
import java.util.function.Consumer
import jakarta.validation.Valid

@Requires(property = "spec.name", value = "MailControllerTest") (1)
@Singleton
@Replaces(AsyncSesEmailSender::class)
@Named(AsyncSesEmailSender.NAME)
open class EmailSenderReplacement : AsyncTransactionalEmailSender<SesRequest, SesResponse> {

    val emails = mutableListOf<Email>()

    override fun getName(): String = AsyncSesEmailSender.NAME

    @Throws(EmailException::class)
    override fun sendAsync(@Valid email: Email,
                           emailRequest: Consumer<SesRequest>): Publisher<SesResponse> {
        emails.add(email)
        return Mono.just(SendEmailResponse.builder().messageId("xxx-yyy-zzz").build())
    }
}
1 Combine @Requires and properties (either via the @Property annotation or by passing properties when starting the context) to avoid bean pollution.

Write a test that uses EmailSenderReplacement to verify that the contents of the email match expectations.

src/test/kotlin/example/micronaut/MailControllerTest.kt
package example.micronaut

import io.micronaut.context.BeanContext
import io.micronaut.context.annotation.Property
import io.micronaut.core.util.CollectionUtils
import io.micronaut.email.AsyncTransactionalEmailSender
import io.micronaut.email.BodyType.HTML
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus.ACCEPTED
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import jakarta.inject.Inject
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test

@Property(name = "spec.name", value = "MailControllerTest") (1)
@MicronautTest (2)
class MailControllerTest(@Client("/") val httpClient: HttpClient) { (3)

    @Inject
    lateinit var beanContext: BeanContext

    @Test
    fun mailSendEndpointSendsAnEmail() {

        val response: HttpResponse<*> = httpClient.toBlocking().exchange<Map<String, String>, Any>(
                HttpRequest.POST("/mail/send", mapOf("to" to "johnsnow@micronaut.example")))
        assertEquals(ACCEPTED, response.status())

        val sender = beanContext.getBean(AsyncTransactionalEmailSender::class.java)
        assertTrue(sender is EmailSenderReplacement)

        val sendgridSender = sender as EmailSenderReplacement
        assertTrue(CollectionUtils.isNotEmpty(sendgridSender.emails as Collection<*>?))
        assertEquals(1, sendgridSender.emails.size)

        val email = sendgridSender.emails[0]
        assertEquals(email.from.email, "john@micronaut.example")
        assertNotNull(email.to)
        assertTrue(email.to!!.stream().findFirst().isPresent)
        assertEquals(email.to!!.stream().findFirst().get().email, "johnsnow@micronaut.example")
        assertEquals(email.subject, "Sending email with Amazon SES is Fun")
        assertNotNull(email.body)
        assertTrue(email.body!![HTML].isPresent)
        assertEquals(email.body!![HTML].get(), "and <em>easy</em> to do anywhere with <strong>Micronaut Email</strong>")
    }
}
1 Combine @Requires and properties (either via the @Property annotation or by passing properties when starting the context) to avoid bean pollution.
2 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
3 Inject the HttpClient bean and point it to the embedded server.

5. Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

5.1. Running the Application

5.1.1. From email address

Change the property mail.email.from.email to match your Amazon SES verified sender.

5.1.2. Supply AWS Credentials

An easy way to supply AWS Credentials is to define the following environment variables:

export AWS_ACCESS_KEY_ID=xxx
export AWS_SECRET_ACCESS_KEY=xxx

5.1.3. Run

To run the application, use the ./gradlew run command, which starts the application on port 8080.

5.1.4. Invoke

curl -d '{"to":"john@micronaut.example"}'
     -H "Content-Type: application/json"
     -X POST http://localhost:8080/mail/send

6. Next steps

Explore more features with Micronaut Guides.

Learn more about Micronaut Email integration.

7. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

8. License

All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…​).