mn create-app example.micronaut.micronautguide \
--features=email-sendgrid,validation,yaml,reactor,graalvm \
--build=gradle \
--lang=java \
--test=junit
Send Emails with SendGrid from the Micronaut Framework
Learn how to send emails with SendGrid from a Micronaut application
Authors: Sergio del Amo, Sergio del Amo
Micronaut Version: 4.6.3
1. Getting Started
In this guide, we will create a Micronaut application written in Java.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOME
configured appropriately
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.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
If you don’t specify the --build argument, Gradle with the Kotlin DSL 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 email-sendgrid
, validation
, yaml
, reactor
, and graalvm
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.
package example.micronaut;
import com.sendgrid.Request;
import com.sendgrid.Response;
import io.micronaut.email.AsyncEmailSender;
import io.micronaut.email.Email;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import static io.micronaut.email.BodyType.HTML;
@Controller("/mail") (1)
public class MailController {
private static final Logger LOG = LoggerFactory.getLogger(MailController.class);
private final AsyncEmailSender<Request, Response> emailSender;
public MailController(AsyncEmailSender<Request, Response> emailSender) { (2)
this.emailSender = emailSender;
}
@Post("/send") (3)
public Publisher<HttpResponse<?>> send(@Body("to") String to) { (4)
return Mono.from(emailSender.sendAsync(Email.builder()
.to(to)
.subject("Sending email with Twilio Sendgrid is Fun")
.body("and <em>easy</em> to do anywhere with <strong>Micronaut Email</strong>", HTML)))
.doOnNext(rsp -> {
LOG.info("response status {}\nresponse body {}\nresponse headers {}",
rsp.getStatusCode(), rsp.getBody(), rsp.getHeaders());
}).map(rsp -> rsp.getStatusCode() >= 400 ?
HttpResponse.unprocessableEntity() :
HttpResponse.accepted()); (5)
}
}
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:
---
micronaut:
email:
from:
email: 'john@micronaut.example'
This is possible thanks to Email Decorators.
4.3. SendGrid
SendGrid is a transactional email service.
SendGrid is responsible for sending billions of emails for some of the best and brightest companies in the world.
4.3.1. SendGrid API Key
To use the Micronaut Sendgrid integration, you need an API Key.
You need to configure the sendgrid.api-key
property. However, don’t put it in application.yml
. It’s a password. Expose it via the SENDGRID_API_KEY
environment variable, using a secret manager or create an environment specific configuration file that won’t be included in source version control.
4.3.2. Dependency
Because we added the email-sendgrid
feature, the application contains the following dependency:
implementation("com.micronaut.email:micronaut-email-sendgrid")
4.4. Test
Create a test bean that replaces the bean of type AsyncTransactionalEmailSender.
package example.micronaut;
import com.sendgrid.Request;
import com.sendgrid.Response;
import io.micronaut.context.annotation.Replaces;
import io.micronaut.context.annotation.Requires;
import io.micronaut.email.AsyncEmailSender;
import io.micronaut.email.AsyncTransactionalEmailSender;
import io.micronaut.email.Email;
import io.micronaut.email.EmailException;
import jakarta.inject.Named;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import static io.micronaut.http.HttpStatus.ACCEPTED;
@Requires(property = "spec.name", value = "MailControllerTest") (1)
@Singleton
@Replaces(AsyncEmailSender.class)
@Named(EmailSenderReplacement.NAME)
class EmailSenderReplacement implements AsyncTransactionalEmailSender<Request, Response> {
public static final String NAME = "sendgrid";
final List<Email> emails = new ArrayList<>();
@Override
public String getName() {
return NAME;
}
@Override
public Publisher<Response> sendAsync(@NotNull @Valid Email email,
@NotNull Consumer<Request> emailRequest) throws EmailException {
emails.add(email);
Response response = new Response();
response.setStatusCode(ACCEPTED.getCode());
return Mono.just(response);
}
public List<Email> getEmails() {
return emails;
}
}
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.
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.Email;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
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.Test;
import java.util.Collections;
import static io.micronaut.email.BodyType.HTML;
import static io.micronaut.http.HttpStatus.ACCEPTED;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Property(name = "spec.name", value = "MailControllerTest") (1)
@MicronautTest (2)
public class MailControllerTest {
@Inject
@Client("/")
HttpClient httpClient; (3)
@Inject
BeanContext beanContext;
@Test
void getMailSendEndpointSendsAnEmail() {
HttpResponse<?> response = httpClient.toBlocking().exchange(
HttpRequest.POST("/mail/send",
Collections.singletonMap("to", "johnsnow@micronaut.example")));
assertEquals(ACCEPTED, response.status());
AsyncTransactionalEmailSender<?, ?> sender = beanContext.getBean(AsyncTransactionalEmailSender.class);
assertTrue(sender instanceof EmailSenderReplacement);
EmailSenderReplacement sendgridSender = (EmailSenderReplacement) sender;
assertTrue(CollectionUtils.isNotEmpty(sendgridSender.emails));
assertEquals(1, sendgridSender.emails.size());
Email email = sendgridSender.emails.get(0);
assertEquals(email.getFrom().getEmail(), "john@micronaut.example");
assertNotNull(email.getTo());
assertTrue(email.getTo().stream().findFirst().isPresent());
assertEquals(email.getTo().stream().findFirst().get().getEmail(), "johnsnow@micronaut.example");
assertEquals(email.getSubject(), "Sending email with Twilio Sendgrid is Fun");
assertNotNull(email.getBody());
assertTrue(email.getBody().get(HTML).isPresent());
assertEquals(email.getBody().get(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.
6. Running the Application
6.1. API Key
Set the SendGrid API Key as an environment variable before you run the application:
export SENDGRID_API_KEY=xxx
6.2. From email address
Change the property micronaut.email.from.email
to match your SendGrid configuration.
6.3. Run
To run the application, use the ./gradlew run
command, which starts the application on port 8080.
6.4. Invoke
curl -d '{"to":"john@micronaut.example"}' \
-H "Content-Type: application/json" \
-X POST http://localhost:8080/mail/send
7. Next Steps
Explore more features with Micronaut Guides.
Learn more about Micronaut Email integration.
8. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
9. 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…). |