Sending Contact Form Messages to Your Email Inbox
Tags: webdev, javascript, productivity, html
Published: 2021-02-21 19:06:44

---
title: Sending Contact Form Messages to Your Email Inbox
published: true
description: A brief tutorial on how to set up serverless websites contact forms to send messages to email inboxes.
tags: webdev, javascript, productivity, html
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pczga764b7200dummamx.jpg
canonical_url: https://jamesinkala.com/blog/sending-contact-form-messages-to-your-email-inbox/
---


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.
![Choose account settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srgx9fz3qwzqval9wxn3.png)

On the 'Senders & Domains' card click on 'Add a Sender Domain or Address'.
![Select 'Add a sender domain ir address](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0g4322cdkstcfebgyzs.png)

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.
![Create sender address](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/057yen4k8c4djavjomon.png)

####Get Maijet API KEYS###
Head to your Mailjet account and open Account Settings on the right navigation dropdown.
![Choose account settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srgx9fz3qwzqval9wxn3.png)

On the 'REST API' card click on 'Master API Key & Sub API key management'.
![Select 'master API keys and& sub API key management](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2o2jivigch51uh4nlspc.png)
Create your 'Master API Key' which will give you two keys, a **SECRET KEY** and an **API KEY**
![Create master key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4c9uz50c6w5kl829bgj3.png)

##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](https://github.com/cure53/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.
![Programmer nightmare](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5f3cloaf8jduis3nrosn.jpg)
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](https://www.npmjs.com/package/dotenv) NodeJs module.
```sh
$ 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](https://www.npmjs.com/package/node-mailjet), go ahead and install that.
```sh
$ 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.
```js
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.