Since placing plain emails on your websites is bad practice (kudos to all those spam-bots scouring the internet) contact forms are the best way to go when it comes to receiving any valuable messages from your users. Not only do they help avoiding spam emails and other unpleasant experiences they simplify sending messages and give you the ability to tailor the kind of message your users can send since they are enriched with all the possible form fields that can be used to do just that.
On this post I am going to demonstrate how you can receive the contact form messages from your website inside your e-mail inbox with the help of Mailjet. I'd assume such a setup would be more preferable in a server-less setup and this will be the format this post will be attuned to.
Before proceeding, start with creating a Mailjet account and validate it.
Setting Up The Environment
Before getting our hands dirty with the code we'll begin with getting Mailjet up and ready to send our emails by adding the sender address and setting up the keys that will be used within Mailjet's NodeJs wrapper.
Add Mailjet Sender Address
Head to your Mailjet account and open Account Settings on the right navigation dropdown.
On the 'Senders & Domains' card click on 'Add a Sender Domain or Address'.
Proceed to adding sender email by adding an email account you already own and proceed with the prompted instructions validate and complete the setup. We set this up as Mailjet will not allow us to send emails from non-existing email addresses.
Get Maijet API KEYS
Head to your Mailjet account and open Account Settings on the right navigation dropdown.
On the 'REST API' card click on 'Master API Key & Sub API key management'.
Create your 'Master API Key' which will give you two keys, a SECRET KEY and an API KEY
Sending The Form Messages as Email
To send the messages we'll need to create the necessary contact form which will provide us with the data to work with in the Javascript part. Get creative and set one up.
The Javascript
Since we are dealing with user input sanitizing it is a good security practice, you can set up any user input sanitizing method you are familiar with, a good start can be DOMPurify.
Avoiding accidents such as your secret API keys ending up on public repositories using a .env file on your local machine might be the way to go.
Use the dedicated ways to set up your API keys on respective production environments which most provide and expose the keys for you in the process.env global variable such as Netlify which allows you to access the environment variables within it's serverless functions.
To access environment keys on both the local and production environments install and use the dotenv NodeJs module.
$ npm install dotenv
One of the ways we can send emails with Mailjet in a javascsript environment is by using their official npm module node-mailjet, go ahead and install that.
$ npm install node-mailjet
Suppose the contact form is made up of three input fields giving us three variables to work with a senderName, a senderEmail and a senderMessage we are going to send that as an email as follows.
require('dotenv').config();
const mailjet = require('node-mailjet').connect(process.env.MAILJET_API_KEY, process.env.MAILJET_API_SECRET)
try {
mailjet
.post("send", {'version': 'v3.1'})
.request({
"Messages":[
{
"From": {
"Email": `${senderEmail}`,
"Name": `Some Website (mywebsite.com)`
},
"To": [
{
"Email": "receivingaddress@somedomain.com",
"Name": "My Name"
}
],
"Subject": "Contact Form Message From mywebsite.com.",
"TextPart": `Name: ${senderName} \n Email: ${senderEmail} \n \n `,
"HTMLPart": `Customer Name: ${senderName}<br> Customer
Email: ${senderEmail}<br> <p>${sendermessage}</p>`
}
]
})
} catch(e) {
// Deal With Error
console.log(e)
}
Another good practice with handling contact forms is informing the sender on the status of the message they have just sent. Let them know that their message has been received and you'll get back at them or to re-try sending it in case of some error with a simple and creative notification. Don't leave the form bland and lifeless.
That's all for this tutorial, go ahead and wreck the contact forms.
Top comments (4)
No, wait. Don't proces.env variables get inserted at runtime? Like, can't you just get the api keys by opening devtools, going to Application > Frames > Scripts, and searching for "require('node-mailjet').connect" ?
Yes they do, I was being more general and didn't want it to be a segue into a detailed explanation on process.env and serverless functions. Have realized the need for precision on what I was talking about and have done just that. Thanks for pointing that out 👍.
Thanks for the response. But then how do you do frontend api call without exposing your api secret key? Seems to me, the only way to do this would be via a server-side function of some sort?
The secret keys are only accessed by the server-side function, the front end just makes API calls and has no access to the keys.