DEV Community

Adam Miedema
Adam Miedema

Posted on • Originally published at Medium on

Sending emails with Alpas web framework — Part 2

Sending emails with Alpas web framework — Part 2

Photo by Mikaela Wiedenhoff on Unsplash

Previously, we captured an email via a Stripe purchase flow and generated a test email within the Alpas framework.

Now, let’s hook this all up with an email service and deliver a real email! 💌

Add mail service dependency

For this example, we’ll use SparkPost as our email service provider and add the dependency to the build.gradle file.

Add the following line to the list of dependencies:

implementation 'com.sparkpost:sparkpost-lib:0.21'

After adding, refresh Gradle to import SparkPost into the project.

Create a driver

Now that we have SparkPost added to our project, we can now create a mail driver. I added a new folder titled ‘drivers’ under the kotlin directory and then created a new file named SparkPostMailDriver.kt.

class SparkPostDriver(private val env: Environment) : MailDriver {
    override fun send(mail: MailMessage) {
        val apiKey = env("SPARKPOST_API_KEY")
        val defaultFromAddress = env("MAIL_FROM_ADDRESS")

        val client = Client(apiKey)
        client.sendMessage(defaultFromAddress, mail.to, mail.subject, mail.message, mail.message)
    }
}

You can see that the class refers to an API Key and a default ‘from’ email address that are located in the .env file. You will first need to setup your SparkPost account and ensure you correctly set up your domain with them as well as create an API key. Once you do that, you can then add those values to your .env file. Just an fyi — SparkPost will take a little time to fully enable sending an email.

Update the mail config

Let’s now register the new driver in the MailConfig.kt file.

Simply, add the following to the init:

addDriver("sparkpost", lazy {  
  SparkPostDriver(env)
} )

Call the new driver in send the message function

Last step, go to start.kt, where we were previously sending the email via our local, and we will explicitly call the SparkPost driver to send our emails thru.

Simply, add “sparkpost” to the driver as shown below:

call.config<MailConfig>().driver("sparkpost").send(mail)

Send a real email!

Everything is now setup to send a real-life email to a real-life inbox. Run your project, fill in the email and credit card text fields, and then click Pay.

Our payment will be successful and a receipt will be sent to the provided email. ✉️ 🎉


In the next part, we will take a look at queues! 😍

Top comments (0)