Hello world, but with asynchronous reply by email
Send email asynchronously in a Java Poja application using events, queues, and workers.
Goal
We want to add asynchronous email sending to a Hello World Application hosted on Poja. It exposes the /hello?to=email@address.com endpoint, returns ... world!, and sends an email to the specified address.
How-to in 2 steps
Step 1: Add email sending to your endpoint
package com.my.company.endpoint.rest.controller;
import com.my.company.mail.Email;
import com.my.company.mail.Mailer;
import jakarta.mail.internet.InternetAddress;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@AllArgsConstructor
public class HelloWorldController {
private final Mailer mailer;
@GetMapping("/hello")
@SneakyThrows
public String helloWorld(@RequestParam String to) {
var email =
new Email(
new InternetAddress(to),
List.of(),
List.of(),
"Hello",
"... world!",
List.of());
mailer.accept(email);
return "... world!";
}
}Step 2: Make it asynchronous
Update the environment configuration
Select the preprod environment to update. Click an Edit button in the Poja Configuration section. Then:
Add 1 worker in the Workers section
Click on the Save button at the bottom

Write the asynchronous code
In the context of Poja, asychronous code refers to an Event driven code executing in Workers. Follow the instructions below to write the asynchronous email sending:
Create the event class
SendEmailRequestedwith the propertytowhich refers to the recipient address of the email inside the packagecom.my.company.endpoint.event.modelCreate the service
SendEmailRequestedServicewhich will consume the event object and send the email inside the packagecom.my.company.service.eventProduce the event when the user sends a request to the
/helloendpoint and provides an email address
Now update the previously created HelloWorldController to produce an event instead of directly sending the email:
Deploy
To trigger a deployment, just commit and push the code to the preprod branch of the repository. Wait. And voilà!

... world!.
Last updated
Was this helpful?
