Fork me on GitHub

Sending mail


Ninja allows you to send mails in a really simple and straightforward manner. All you have to do is to configure your SMTP server in application.conf. Then you can inject Postoffice and Mail in your application. This allows you to create a new Mail instance and send it via the Postoffice.

Basic usage and configuration

The first step is to configure your mail server in application.conf. You can do so by using the following parameters:     // Hostname of the smtp server (e.g.
smtp.port=...     // Port of the smtp server  (e.g. 465).
smtp.ssl=...      // Whether to enable ssl (true or false)
smtp.user=...     // Username to access the smtp server
smtp.password=... // The password
smtp.debug=...    // Enable logging of a huge amount of debug information (true or false)

If you want to send a mail you can inject the Postoffice and a Provider for Mail into your class.

public class MailController {

    Provider<Mail> mailProvider;

    Postoffice postoffice;

    public void sendMail() {
        Mail mail = mailProvider.get();

        // fill the mail with content:



        mail.addHeader("header1", "value1");
        mail.addHeader("header2", "value2");






        // finally send the mail
        try {
        } catch (EmailException | AddressException e) {
            // ...

Mail in development and in testing

When Ninja is running in test or dev mode Postoffice will be implemented by PostofficeMockImpl by default.

PostofficeMockImpl does not send mails, but stores mails, so you can check if they would have been sent in reality via getLastSentMail().

PostofficeMockImpl also prints out emails that would have been sent to the system.out. This is nice if you are developing your application but don’t want to check your email account to see if something has been sent.

Advanced usage

Specifying own Postoffice implementation

You can override the implementation that will be used via the following parameter in application.conf:

postoffice.implementation=... // Implementation to use for interface Postoffice

If you want to use the real SMTP Postoffice in dev mode (and not the mocked Postoffice by default) you can override that behavior with the parameter: