Sending E-Mails with Adonis Js and Mailgun

Sending E-Mails with Adonis Js and Mailgun

·

2 min read

Almost every application being built today requires some communication, and if you are building an application right now, odds are you will need to implement some sort of communication with the user over e-mail at some point.

Adonis js is a Node js framework that makes it easy for developers to build applications incredibly fast and with relative ease. With Adonis js, you can easily send e-mails to users of your application using the Mailgun e-mail service. How would you do that?

First, you will need to add the Adonis Mail Provider by running the following:

adonis install @adonisjs/mail

After that, you need to register the Mail provider in the start/app.js file like so:

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

Go over to the config/mail.js file where you would see something like this:

smtp: {
driver: "smtp",
pool: true,
port: Env.get("SMTP_PORT", 2525),
host: Env.get("SMTP_HOST"),
secure: false,
auth: {
user: Env.get("MAIL_USERNAME"),
pass: Env.get("MAIL_PASSWORD"),
},
maxConnections: 5,
maxMessages: 100,
rateLimit: 10,
},

To be able to use this service you need a Mailgun account so head over here to start. After registering, click the ‘Sending’ drop-down and select ‘Overview’,

1_aVkoolNXmmMMxgOOd5HrIA.png

Under the Overview tab, select SMTP, your SMTP data will appear below. It looks like this:

Grab your SMTP credentials:
SMTP hostname: smtp.mailgun.org
Port: 587 (recommended)
Username: postmaster@*************.mailgun.org
Default password: ******************

With your SMTP credentials you can now properly format your Mail Provider like so:

smtp: {
driver: "smtp",
pool: true,
port: Env.get("SMTP_PORT", 587),
host: Env.get("SMTP_HOST", "smtp.mailgun.org"),
secure: false,
auth: {
user: Env.get("MAIL_USERNAME"),
pass: Env.get("MAIL_PASSWORD"),
},
maxConnections: 5,
maxMessages: 100,
rateLimit: 10,
},

You can also see that we are fetching the MAIL_USERNAME and MAIL_PASSWORD from .env so add it to your .env file just like below:

MAIL_USERNAME=postmaster@***********************.mailgun.org
MAIL_PASSWORD=*********************

Also, ensure that your Mail Provider connection is SMTP like this:

connection: Env.get("MAIL_CONNECTION", "smtp"),

With this, you can now send your E-mail using the Adonis Mail Provider

await Mail.send("emails.welcome", data, (message) => {
message.to(user.email, user.name)
.from("noreply@my-website.com", "My Website")
.subject("Welcome to My Website");
});

Don’t forget to use your Mail Provider in your controller, otherwise, you would have yourself to blame, lol.

const Mail = use("Mail");

Now build something awesome!

1_53dqvzTI5Osxr3aSnZRaEg.gif