Sending emails with Alpas web framework — Part 1
Previously, I showed you an example of integrating Stripe payments with Alpas and providing the Kotlin equivalent to some other examples provided by Stripe. Then, in a follow-up post, I showed how concise Alpas is as a framework by reducing that example even further.
Now, I am going to work off of that latest example and show how you can capture an email address and send an order confirmation email. This will be a multi-post series and, in this post, I’ll lay down the foundation of capturing an email and making it available to the Alpas back-end.
Get the front-end ready
To get started, I’ll make some updates to the front-end to expose an input field for the user to enter their email as well as update the javascript to send the email to the back-end when Stripe confirms a successfully processed payment.
In the welcome.peb file, all I need to do is add an input to the form.
<input id="email" placeholder="your@email.address">
Then, in the client.js file, we’ll append some code to the payment successful statement.
else {
// The payment succeeded!
var email = document.getElementById("email").value;
orderComplete(result.paymentIntent.id);
fetch("/payment-success", {
method: "POST",
headers: {
"Content-Type": "application/json",
'X-CSRF-TOKEN': document.head.querySelector(" [name~=csrf-token][content]").content
},
body: email
});
}
The above will take the value entered into the email input field and then post it to the back-end given a successful payment has been verified by Stripe.
Get the back-end ready
Now that the front-end captures and sends the email for a successful order to the back-end, let’s use this email to send an email to the user confirming their order.
In the start.kt file, I’ll add the following route to receive the user’s email and then call a function to send an email.
post("payment-success") {
send(this)
}
Now, I’ll add the send function that will compile the email contents and call an action to send the email.
fun send(call: HttpCall) {
val mail = MailMessage().apply {
to = call.body
subject = "Order Confirmed"
message = "Here is your order receipt!"
}
call.config<MailConfig>().driver().send(mail)
}
Test our progress
Alpas comes packaged with email features that make crafting and sending emails super easy and, at this juncture, we can already do a pretty solid test.
Running the project on my local renders this:
Now, adding an email address, a Stripe test credit card, and clicking ‘Pay’ shows:
Alpas holds onto a preview of the email if there is nowhere for the email to go. In the project, navigating to storage > mails shows records of created emails. Here is the email that was generated from the actions above.
Just a couple lines of code got us pretty far with generating an order confirmation email with the Alpas framework. In the next part, we will look at how we can hook this all up to an email service to send a real-life email.
Top comments (0)