Groovy / Gradle

Oracle Cloud Infrastructure (OCI) Email Delivery using the Micronaut framework

Learn how to send an email with Oracle Cloud Infrastructure (OCI) Email Delivery using the Micronaut framework.

Hari Krishna Sivvala, Burt Beckwith
On this guide
In this section

Getting Started

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

We’ll use Micronaut Email to send emails with the Jakarta Mail API, using the Oracle Cloud Infrastructure (OCI) Email Delivery Service.

What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • An Oracle Cloud account (create a free trial account at signup.oraclecloud.com)

  • Oracle Cloud CLI installed with local access to Oracle Cloud configured by running oci setup config

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.

Setup OCI Email Delivery

To configure email delivery, we need to:

  • add an "Approved Sender"

  • generate SMTP credentials

  • find the SMTP endpoint for your region.

Approved Sender

The approved sender is a regular user. The user must be granted permission to send emails via an IAM policy statement, so we’ll add the user to a new group and grant permission to the group to support future approved email senders.

Create a new group

Create a group by running:

oci iam group create --description "email sender group" --name "mn-email-group"

The response should look like this:

{
  "data": {
    "compartment-id": "ocid1.tenancy.oc1..aaaaaaaa...",
    "description": "email sender group",
    "id": "ocid1.group.oc1..aaaaaaaaqx...",
    "inactive-status": null,
    "lifecycle-state": "ACTIVE",
    "name": "mn-email-group",
    ...
  }
}

Save the group id as an environment variable:

export GRP_ID='ocid1.group.oc1..aaaaaaaaqx...'
Note

We use Linux/Mac syntax for environment variables. If you use Windows, change 'export' to 'set' if using the cmd prompt, for example:

set VARNAME=<VALUE>

and if using PowerShell, change 'export ' to '$' and use quotes around the value, for example:

$VARNAME="<VALUE>"

To dereference a value in Linux/Mac or Powershell, use $, for example:

/some/command -option=$VARNAME

and if using cmd, use % before and after the name, for example

/some/command -option=%VARNAME%

Create a new user

Create a user by running:

oci iam user create --description "email sender" --name "mn-email-user"

The response should look like this:

{
  "data": {
    "compartment-id": "ocid1.tenancy.oc1..aaaaaaaaud4g...",
    "description": "email sender",
    "id": "ocid1.user.oc1..aaaaaaaaqx...",
    "lifecycle-state": "ACTIVE",
    "name": "mn-email-user",
    ...
  }
}

Save the user id as an environment variable:

export USR_ID='ocid1.user.oc1..aaaaaaaaqx...'

Add the user to the group

oci iam group add-user --group-id $GRP_ID --user-id $USR_ID

Compartment OCID

Find the OCID of the compartment where the IAM policy will be created. Run this to list the compartments in your root compartment:

oci iam compartment list

and find the compartment by the name or description in the JSON output. It should look like this:

{
  "compartment-id": "ocid1.tenancy.oc1..aaaaaaaaud4g4e5ovjaw...",
  "description": "Micronaut guides",
  "id": "ocid1.compartment.oc1..aaaaaaaarkh3s2wcxbbm...",
  "lifecycle-state": "ACTIVE",
  "name": "micronaut-guides",
  ...
}

Save the compartment id as an environment variable:

export C='ocid1.compartment.oc1..aaaaaaaarkh3s2wcxbbm...'

IAM policy

Create an IAM policy to grant members of the group permission to send emails:

For Linux or Mac, run:

oci iam policy create -c $C --description "mn-email-guide-policy" \
 --name "mn-email-guide-policy" \
 --statements '["Allow group mn-email-group to use email-family in compartment id ocid1.compartment.oc1..aaaaaaaarkh3s2wcxbbm..."]'

or for Windows:

oci iam policy create -c %C% --description "mn-email-guide-policy" \
 --name "mn-email-guide-policy" \
 --statements "[\"Allow group mn-email-group to use email-family in compartment id %C%\"]"

Generate SMTP credentials

Generate SMTP credentials for the user by running:

oci iam smtp-credential create --description "mn-email-user smtp credentials" --user-id $USR_ID

The response should look like this:

{
  "data": {
    "description": "mn-email-user smtp credentials",
    "id": "ocid1.credential.oc1..aaaaaaaal...",
    "lifecycle-state": "ACTIVE",
    "password": "nB$O;.......",
    "user-id": "ocid1.user.oc1..aaaaaaaaqx...",
    "username": "ocid1.user.oc1..aaaaaaaaqx...@ocid1.tenancy.oc1..aaaaaaaa....me.com"
  }
}

Save the username and password from the response; we’ll need those later.

Add an approved sender

oci email sender create -c $C --email-address noreply@test.com
Note
email-address is the "from" address.

SMTP Endpoint

Each region in Oracle Cloud has an SMTP endpoint to use as the SMTP server address. Find the endpoint for your region and save the URL, e.g., smtp.email.us-ashburn-1.oci.oraclecloud.com; we’ll need that for the application configuration.

Writing the Application

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

mn create-app example.micronaut.micronautguide --build=gradle --lang=groovy
Note
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.

Add Dependencies

Add these dependencies to your build to add email support. Only the first is required; if you won’t be using templates for emails you can omit the other two:

build.gradle
implementation("io.micronaut.email:micronaut-email-javamail")
implementation("io.micronaut.email:micronaut-email-template")
implementation("io.micronaut.views:micronaut-views-thymeleaf")

Create a SessionProvider

Micronaut Email requires a bean of type SessionProvider when using JavaMail to create a Session. Create the OciSessionProvider class:

groovy/src/main/groovy/example/micronaut/OciSessionProvider.groovy

EmailController class

Create a controller that uses the Micronaut EmailSender to send emails:

groovy/src/main/groovy/example/micronaut/EmailController.groovy

Email template

Create a Thymeleaf template in:

src/main/resources/views/email.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
    <p>
        Hello, <span th:text="${name}"></span>!
    </p>
</body>

From Configuration

If you always use the same sender, you can add the following configuration snippet to application.properties:

src/main/resources/application.properties

SMTP configuration

Add the following snippet to application.properties to supply the SMTP credentials.

We injected SMTP configuration via constructor parameters annotated with @Property. You could have used a POJO annotated with @ConfigurationProperties as well.

src/main/resources/application.properties

Java Mail Properties Configuration

Add the following snippet to application.properties to supply JavaMail properties:

src/main/resources/application.properties

Set Configuration Variables

It’s best to avoid hard-coding credentials and other sensitive information directly in config files. By using placeholder variables in application.properties like SMTP_PASSWORD and SMTP_USER, we can externalize the values via environment variables or secure storage such as Oracle Cloud Infrastructure (OCI) Vault.

For simplicity, we’ll use environment variables. Set the "from" email to the value you used earlier, and choose a "from" name. Set the SMTP username and password from the values you saved earlier when you generated the SMTP credentials, and set the SMTP server as the regional endpoint:

export FROM_EMAIL='noreply@test.com'
export FROM_NAME='noreply'
export SMTP_PASSWORD='nB$O;.......'
export SMTP_USER='ocid1.user.oc1..aaaaaaaaqx...@ocid1.tenancy.oc1..aaaaaaaa....me.com'
export SMTP_HOST='smtp.email.us-ashburn-1.oci.oraclecloud.com'

Writing Tests

Create a test class to ensure emails are sent successfully:

groovy/src/test/groovy/example/micronaut/EmailControllerSpec.groovy

Create src/test/resources/application-test.properties. Micronaut applies this configuration file only for the test environment.

src/test/resources/application-test.properties
micronaut.email.from.email=test@test.com
micronaut.email.from.name=Email Test
smtp.password=password
smtp.user=user
javamail.properties.mail.smtp.host=smtp.com

Testing the Application

To run the tests:

./gradlew test

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

Running the Application

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

Run some cURL requests to test the application:

Send a simple plain-text email:

curl -X POST localhost:8080/email/basic

Send a templated email:

curl -X POST localhost:8080/email/template/test

Send an email with an attachment. If you use Mac/Linux, run

curl -X POST \
     -H "Content-Type: multipart/form-data" \
     -F "file=@/Users/test/Pictures/demo/email.jpg" \
     localhost:8080/email/attachment

and run this if using Windows:

curl -X POST \
     -H "Content-Type: multipart/form-data" \
     -F "file=@C:\Users\username\Downloads\email.png" \
     localhost:8080/email/attachment

Next Steps

Read more about the Micronaut Email project.

Learn about the OCI Email Delivery Service.

See this blog post which covers much of the same material as this guide.

License

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