Mailer Reference Guide

This guide is the companion from the Mailer Getting Started Guide. It explains in more details the configuration and usage of the Quarkus Mailer.

Mailer extension

To use the mailer, you need to add the quarkus-mailer extension.

You can add the extension to your project using:

> ./mvnw quarkus:add-extensions -Dextensions="mailer"

Or just add the following dependency to your project:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-mailer</artifactId>
</dependency>

Accessing the mailer

You can inject the mailer in your application using:

@Inject
Mailer mailer;

@Inject
ReactiveMailer reactiveMailer;

There are 2 APIs:

  • io.quarkus.mailer.Mailer provides the imperative (blocking and synchronous) API;

  • io.quarkus.mailer.reactive.ReactiveMailer provides the reactive (non-blocking and asynchronous) API

The two APIs are equivalent feature-wise. Actually the Mailer implementation is built on top of the ReactiveMailer implementation.
Deprecation

io.quarkus.mailer.ReactiveMailer is deprecated in favor of io.quarkus.mailer.reactive.ReactiveMailer.

To send a simple email, proceed as follows:

// Imperative API:
mailer.send(Mail.withText("to@acme.org", "A simple email from quarkus", "This is my body."));
// Reactive API:
Uni<Void> stage = reactiveMailer.send(Mail.withText("to@acme.org", "A reactive email from quarkus", "This is my body."));

For example, you can use the Mailer in an HTTP endpoint as follows:

@GET
@Path("/imperative")
public void sendASimpleEmail() {
    mailer.send(Mail.withText("to@acme.org", "A simple email from quarkus", "This is my body"));
}

@GET
@Path("/reactive")
public Uni<Void> sendASimpleEmailAsync() {
    return reactiveMailer.send(
            Mail.withText("to@acme.org", "A reactive email from quarkus", "This is my body"));
}

Creating Mail objects

The mailer lets you send io.quarkus.mailer.Mail objects. You can create new io.quarkus.mailer.Mail instances from the constructor or from the Mail.withText and Mail.withHtml helper methods. The Mail instance lets you add recipients (to, cc, or bcc), set the subject, headers, sender (from) address…​

You can also send several Mail objects in one call:

mailer.send(mail1, mail2, mail3);

Sending attachments

To send attachments, just use the addAttachment methods on the io.quarkus.mailer.Mail instance:

@GET
@Path("/attachment")
public void sendEmailWithAttachment() {
        mailer.send(Mail.withText("clement.escoffier@gmail.com", "An email from quarkus with attachment",
                "This is my body")
                .addAttachment("my-file-1.txt",
                        "content of my file".getBytes(), "text/plain")
                .addAttachment("my-file-2.txt",
                        new File("my-file.txt"), "text/plain")
        );
}

Attachments can be created from raw bytes (as shown in the snippet) or files. Note that files are resolved from the working directory of the application.

Sending HTML emails with inlined attachments

When sending HTML emails, you can add inlined attachments. For example, you can send an image with your email, and this image will be displayed in the mail content. If you put the image file into the META-INF/resources folder, you should specify the full path to the file, e.g. META-INF/resources/quarkus-logo.png otherwise Quarkus will look for the file in the root directory.

@GET
@Path("/html")
public void sendingHTML() {
    String body = "<strong>Hello!</strong>" + "\n" +
        "<p>Here is an image for you: <img src=\"cid:my-image@quarkus.io\"/></p>" +
        "<p>Regards</p>";
    mailer.send(Mail.withHtml("to@acme.org", "An email in HTML", body)
        .addInlineAttachment("quarkus-logo.png",
            new File("quarkus-logo.png"),
            "image/png", "<my-image@quarkus.io>"));
}

Note the content-id format and reference. By spec, when you create the inline attachment, the content-id must be structured as follows: <id@domain>. If you don’t wrap your content-id between <>, it is automatically wrapped for you. When you want to reference your attachment, for instance in the src attribute, use cid:id@domain (without the < and >).

Message Body Based on Qute Templates

It’s possible to inject a mail template, where the message body is created automatically using Qute templates.

@Path("")
public class MailingResource {

    @CheckedTemplate
    static class Templates {
        public static native MailTemplateInstance hello(String name); (1)
    }

    @GET
    @Path("/mail")
    public Uni<Void> send() {
        // the template looks like: Hello {name}! (2)
        return Templates.hello("John")
           .to("to@acme.org")  (3)
           .subject("Hello from Qute template")
           .send(); (4)
    }
}
1 By convention, the enclosing class name and method names are used to locate the template. In this particular case, we will use the src/main/resources/templates/MailingResource/hello.html and src/main/resources/templates/MailingResource/hello.txt templates to create the message body.
2 Set the data used in the template.
3 Create a mail template instance and set the recipient.
4 MailTemplate.send() triggers the rendering and, once finished, sends the e-mail via a Mailer instance.
Injected mail templates are validated during build. The build fails if there is no matching template in src/main/resources/templates.

You can also do this without type-safe templates:

@Inject
@Location("hello")
MailTemplate hello; (1)

@GET
@Path("/mail")
public Uni<Void> send() {
    return hello.to("to@acme.org") (2)
       .subject("Hello from Qute template")
       .data("name", "John") (3)
       .send() (4)
}
1 If there is no @Location qualifier provided, the field name is used to locate the template. Otherwise, search for the template as the specified location. In this particular case, we will use the src/main/resources/templates/hello.html and src/main/resources/templates/hello.txt templates to create the message body.
2 Create a mail template instance and set the recipient.
3 Set the data used in the template.
4 MailTemplate.send() triggers the rendering and, once finished, sends the e-mail via a Mailer instance.

Execution model

The reactive mailer is non-blocking, and the results are provided on an I/O thread. See the Quarkus Reactive Architecture documentation for further details on this topic.

The non-reactive mailer blocks until the messages are sent to the SMTP server. Note that does not mean that the message is delivered, just that it’s been sent successfully to the SMTP server, which will be responsible for the delivery.

Testing email sending

Because it is very inconvenient to send emails during development and testing, you can set the quarkus.mailer.mock boolean configuration to true to prevent the actual sending of emails but instead print them on stdout and collect them in a MockMailbox bean instead. This is the default if you are running Quarkus in DEV or TEST mode.

You can then write tests to verify that your emails were sent, for example, by a REST endpoint:

@QuarkusTest
class MailTest {

    private static final String TO = "foo@quarkus.io";

    @Inject
    MockMailbox mailbox;

    @BeforeEach
    void init() {
        mailbox.clear();
    }

    @Test
    void testTextMail() throws MessagingException, IOException {
        // call a REST endpoint that sends email
        given()
        .when()
        .get("/send-email")
        .then()
           .statusCode(202)
           .body(is("OK"));

        // verify that it was sent
        List<Mail> sent = mailbox.getMessagesSentTo(TO);
        assertThat(sent).hasSize(1);
        Mail actual = sent.get(0);
        assertThat(actual.getText()).contains("Wake up!");
        assertThat(actual.getSubject()).isEqualTo("Alarm!");

        assertThat(mailbox.getTotalMessagesSent()).isEqualTo(6);
    }
}

Using the underlying Vert.x Mail Client

The Quarkus Mailer is implemented on top of the Vert.x Mail Client, providing an asynchronous and non-blocking way to send emails. If you need fine control on how the mail is sent, for instance if you need to retrieve the message ids, you can inject the underlying client, and use it directly:

@Inject MailClient client;

Three API flavors are exposed:

  • the Mutiny client (io.vertx.mutiny.ext.mail.MailClient)

  • the bare client (io.vertx.ext.mail.MailClient)

Check the Using Vert.x guide for further details about these different APIs and how to select the most suitable for you.

The retrieved MailClient is configured using the configuration key presented above. You can also create your own instance, and pass your own configuration.

Gmail specific configuration

If you want to use the Gmail SMTP server, first create a dedicated password in Google Account > Security > App passwords or go to https://myaccount.google.com/apppasswords.

You need to switch on 2-Step Verification at https://myaccount.google.com/security in order to access the App passwords page.

When done, you can configure your Quarkus application by adding the following properties to your application.properties:

With TLS:

quarkus.mailer.auth-methods=DIGEST-MD5 CRAM-SHA256 CRAM-SHA1 CRAM-MD5 PLAIN LOGIN
quarkus.mailer.from=YOUREMAIL@gmail.com
quarkus.mailer.host=smtp.gmail.com
quarkus.mailer.port=587
quarkus.mailer.start-tls=REQUIRED
quarkus.mailer.username=YOUREMAIL@gmail.com
quarkus.mailer.password=YOURGENERATEDAPPLICATIONPASSWORD

Or with SSL:

quarkus.mailer.auth-methods=DIGEST-MD5 CRAM-SHA256 CRAM-SHA1 CRAM-MD5 PLAIN LOGIN
quarkus.mailer.from=YOUREMAIL@gmail.com
quarkus.mailer.host=smtp.gmail.com
quarkus.mailer.port=465
quarkus.mailer.ssl=true
quarkus.mailer.username=YOUREMAIL@gmail.com
quarkus.mailer.password=YOURGENERATEDAPPLICATIONPASSWORD

The quarkus.mailer.auth-methods configuration option is needed for the Quarkus mailer to support password authentication with Gmail. By default, both the mailer and Gmail default to XOAUTH2 which requires registering an application, getting tokens, etc.

Using SSL with native executables

Note that if you enable SSL for the mailer and you want to build a native executable, you will need to enable the SSL support. Please refer to the Using SSL With Native Executables guide for more information.

Configuring the SMTP credentials

It is recommended to encrypt any sensitive data, such as the quarkus.mailer.password. One approach is to save the value into a secure store like HashiCorp Vault, and refer to it from the configuration. Assuming for instance that Vault contains key mail-password at path myapps/myapp/myconfig, then the mailer extension can be simply configured as:

...
# path within the kv secret engine where is located the application sensitive configuration
quarkus.vault.secret-config-kv-path=myapps/myapp/myconfig

...
quarkus.mailer.password=${mail-password}

Please note that the password value is evaluated only once, at startup time. If mail-password was changed in Vault, the only way to get the new value would be to restart the application.

For more information about the Mailer configuration please refer to the Configuration Reference.

Configuring a trust store

If your SMTP requires a trust store, you can configure the trust store as follows:

quarkus.mailer.host=...
quarkus.mailer.port=...
quarkus.mailer.ssl=true
quarkus.mailer.trust-store.paths=truststore.jks # the path to your trust store
quarkus.mailer.trust-store.password=secret # the trust store password if any
quarkus.mailer.trust-store.type=JKS # the type of trust store if it can't be deduced from the file extension

Quarkus mailer supports JKS, PKCS#12 and PEM trust stores. For PEM, you can configure multiple files. For JKS and PKCS#12, you can configure the password if any.

quarkus.mailer.trust-store.type is optional and allows configuring the type of trust store (among JKS, PEM and PKCS). When not set, Quarkus tries to deduce the type from the file name.

You can also configure quarkus.mailer.trust-all=true to bypass the verification.

Mailer Configuration Reference

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

Caches data from attachment’s Stream to a temporary file. It tries to delete it after sending email.

Environment variable: QUARKUS_MAILER_CACHE_ATTACHMENTS

boolean

false

Sets the default from attribute when not specified in the io.quarkus.mailer.Mail instance. It’s the sender email address.

Environment variable: QUARKUS_MAILER_FROM

string

Enables the mock mode. When enabled, mails are not sent, but stored in an in-memory mailbox. The content of the emails is also printed on the console. Disabled by default on PROD, enabled by default on DEV and TEST modes.

Environment variable: QUARKUS_MAILER_MOCK

boolean

Sets the default bounce email address. A bounced email, or bounce, is an email message that gets rejected by a mail server.

Environment variable: QUARKUS_MAILER_BOUNCE_ADDRESS

string

Sets the SMTP host name.

Environment variable: QUARKUS_MAILER_HOST

string

localhost

The SMTP port. The default value depends on the configuration. The port 25 is used as default when ssl is disabled. This port continues to be used primarily for SMTP relaying. SMTP relaying is the transmission of email from email server to email server. The port 587 is the default port when ssl is enabled. It ensures that email is submitted securely. Note that the port 465 may be used by SMTP servers, however, IANA has reassigned a new service to this port, and it should no longer be used for SMTP communications.

Environment variable: QUARKUS_MAILER_PORT

int

Sets the username to connect to the SMTP server.

Environment variable: QUARKUS_MAILER_USERNAME

string

Sets the password to connect to the SMTP server.

Environment variable: QUARKUS_MAILER_PASSWORD

string

Enables or disables the TLS/SSL.

Environment variable: QUARKUS_MAILER_SSL

boolean

false

Set whether all server certificates should be trusted. This option is only used when ssl is enabled.

Environment variable: QUARKUS_MAILER_TRUST_ALL

boolean

Sets the max number of open connections to the mail server.

Environment variable: QUARKUS_MAILER_MAX_POOL_SIZE

int

10

Sets the hostname to be used for HELO/EHLO and the Message-ID.

Environment variable: QUARKUS_MAILER_OWN_HOST_NAME

string

Sets if connection pool is enabled. If the connection pooling is disabled, the max number of sockets is enforced nevertheless.

Environment variable: QUARKUS_MAILER_KEEP_ALIVE

boolean

true

Disable ESMTP. The RFC-1869 states that clients should always attempt EHLO as first command to determine if ESMTP is supported, if this returns an error code, HELO is tried to use the regular SMTP command.

Environment variable: QUARKUS_MAILER_DISABLE_ESMTP

boolean

false

Sets the TLS security mode for the connection. Either DISABLED, OPTIONAL or REQUIRED.

Environment variable: QUARKUS_MAILER_START_TLS

string

OPTIONAL

Enables DKIM signing.

Environment variable: QUARKUS_MAILER_DKIM_ENABLED

boolean

false

Configures the PKCS#8 format private key used to sign the email.

Environment variable: QUARKUS_MAILER_DKIM_PRIVATE_KEY

string

Configures the PKCS#8 format private key file path.

Environment variable: QUARKUS_MAILER_DKIM_PRIVATE_KEY_PATH

string

Configures the Agent or User Identifier (AUID).

Environment variable: QUARKUS_MAILER_DKIM_AUID

string

Configures the selector used to query the public key.

Environment variable: QUARKUS_MAILER_DKIM_SELECTOR

string

Configures the Signing Domain Identifier (SDID).

Environment variable: QUARKUS_MAILER_DKIM_SDID

string

Configures the canonicalization algorithm for signed headers.

Environment variable: QUARKUS_MAILER_DKIM_HEADER_CANON_ALGO

simple, relaxed

Configures the canonicalization algorithm for mail body.

Environment variable: QUARKUS_MAILER_DKIM_BODY_CANON_ALGO

simple, relaxed

Configures the body limit to sign. Must be greater than zero.

Environment variable: QUARKUS_MAILER_DKIM_BODY_LIMIT

int

Configures to enable or disable signature sign timestamp.

Environment variable: QUARKUS_MAILER_DKIM_SIGNATURE_TIMESTAMP

boolean

Configures the expire time in seconds when the signature sign will be expired. Must be greater than zero.

Environment variable: QUARKUS_MAILER_DKIM_EXPIRE_TIME

long

Configures the signed headers in DKIM, separated by commas. The order in the list matters.

Environment variable: QUARKUS_MAILER_DKIM_SIGNED_HEADERS

list of string

Sets the login mode for the connection. Either NONE, @{code DISABLED}, OPTIONAL, REQUIRED or XOAUTH2. - DISABLED means no login will be attempted - NONE means a login will be attempted if the server supports in and login credentials are set - REQUIRED means that a login will be attempted if the server supports it and the send operation will fail otherwise - XOAUTH2 means that a login will be attempted using Google Gmail Oauth2 tokens

Environment variable: QUARKUS_MAILER_LOGIN

string

NONE

Sets the allowed authentication methods. These methods will be used only if the server supports them. If not set, all supported methods may be used. The list is given as a space separated list, such as DIGEST-MD5 CRAM-SHA256 CRAM-SHA1 CRAM-MD5 PLAIN LOGIN.

Environment variable: QUARKUS_MAILER_AUTH_METHODS

string

Sets the trust store password if any. Note that the password is only used for JKS and PCK#12 trust stores.

Environment variable: QUARKUS_MAILER_TRUSTSTORE_PASSWORD

string

Sets the location of the trust store files. If you use JKS or PCK#12, only one path is allowed. If you use PEM files, you can specify multiple paths. The relative paths are relative to the application working directly.

Environment variable: QUARKUS_MAILER_TRUSTSTORE_PATHS

list of string

Sets the trust store type. By default, it guesses the type from the file name extension. For instance, truststore.pem will be seen as a PEM file, while truststore.jks will be seen as a JKS file. truststore.p12 and truststore.pfx will both be seen as PKCS#12 files. Accepted values are: JKS, PEM, PKCS.

Environment variable: QUARKUS_MAILER_TRUSTSTORE_TYPE

string

Whether the mail should always been sent as multipart even if they don’t have attachments. When sets to true, the mail message will be encoded as multipart even for simple mails without attachments.

Environment variable: QUARKUS_MAILER_MULTI_PART_ONLY

boolean

false

Sets if sending allows recipients errors. If set to true, the mail will be sent to the recipients that the server accepted, if any.

Environment variable: QUARKUS_MAILER_ALLOW_RCPT_ERRORS

boolean

false

Enables or disables the pipelining capability if the SMTP server supports it.

Environment variable: QUARKUS_MAILER_PIPELINING

boolean

true

Sets the connection pool cleaner period. Zero disables expiration checks and connections will remain in the pool until they are closed.

Environment variable: QUARKUS_MAILER_POOL_CLEANER_PERIOD

Duration

PT1S

Set the keep alive timeout for the SMTP connection. This value determines how long a connection remains unused in the pool before being evicted and closed. A timeout of 0 means there is no timeout.

Environment variable: QUARKUS_MAILER_KEEP_ALIVE_TIMEOUT

Duration

PT300S

Sets the workstation used on NTLM authentication.

Environment variable: QUARKUS_MAILER_NTLM_WORKSTATION

string

Sets the domain used on NTLM authentication.

Environment variable: QUARKUS_MAILER_NTLM_DOMAIN

string

About the Duration format

The format for durations uses the standard java.time.Duration format. You can learn more about it in the Duration#parse() javadoc.

You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, PT is implicitly prepended to the value to obtain a standard java.time.Duration format.