Setting up Mailgun with Adonis.js

When I first had to set up automated email sending with Adonis I was glad to see it has pre-baked support for a handful of providers, including Mailgun, which is my prefered one. However struggled a bit when I actually had to set it up. The official documentation is really good, but it also seems to be missing some more concrete steps beyond installing the provider.

One of the many benefits of using the Mail provider is that it allows you to use Edge templates in your emails. And if you have ever tried to send emails before, you already know this is good. 😅

So this guide should help you set up Mailgun with Adonis.js easy as pie.

So assuming that you already have an exsisting project or a brand new one. Go ahead and install the generic mail provider. Adonis 4 comes with a whole new interface for installing official packages. So go ahead and install it with the below command.

$ adonis install @adonisjs/mail

After installing the mail provider we need to include it in start/app.js. After all your other providers, go ahead and include the MailProvider as well.

const providers = [...'@adonisjs/mail/providers/MailProvider']

I will also assume that you already have a Mailgun account setup with a working domain. I won't go over how to do this, but Mailgun has an excellent quickstart guide on how to do this.

What you'll need from Mailgun in order to proceed is an API key along with the domain you have installed. Whenever I use the domain you'll just need to replace it with your own.

So let's configure Adonis to work with Mailgun. I'll be using environment variables to configure my provider and my API key, and you should too. So open your .env file and paste in the below, replacing my dummy key with your actual one.


So Adonis does not come with Mailgun pre-configured. We'll need to do that by hand. It's however quite easy. Open your config/mail.js file and just after the sparkpost object, paste our mailgun object in.

mailgun: {
  driver: 'mailgun',
  domain: Env.get('MAILGUN_DOMAIN'),
  apiKey: Env.get('MAILGUN_API_KEY'),
  extras: {}

We'll be leaving the extras object empty. But Mailgun allows you to configure a bunch of extra stuff here. But in order to keep things tidy, we'll skip that.

And acutally this was all we needed to do. So from now on whenever you want to send an email from your project, you need to import the Mail provider such as below.

const Mail = use('Mail')

And then use it like this:

await Mail.send('emails.test', { name: 'Mads' }, message => {
    .subject('Sending emails with Adonis is easy!')

The above assumes you have an Edge template called "test" in resources/views/emails and that it contains a "name" variable.

Have fun sending emails! 😎