Securely Sending Emails with JavaScript: An Example of JavaScript Code for Email Communication

Emailjs provides authorization API keys for email sending, as browsers do not have the same functionality as mail clients.

The link to access my code for the project can be found at: https://github.com/Iwaniukooo11/email-sender.

In the present day, programmers are required to utilize contemporary features and technologies when developing websites, even for simple projects like creating a portfolio for a friend. However, encountering issues with tasks such as retrieving data from a contact form is not uncommon.
There are various methods available for accessing this data. For instance, one can establish a connection between the form and a database (such as Firebase) to retrieve incoming messages. Although this is a valid option, it may prove challenging for clients who are not technologically inclined.

Why don‘t you do your job by sending email?

Certainly, it is the optimal choice that offers the highest level of user-friendliness. Your clients will greatly appreciate receiving incoming messages without relying on the database. However, the challenge lies in figuring out how to execute this effectively. One might assume that utilizing a backend language is necessary.

Me and my guys waiting for you to send email

Absolutely not! There is no requirement to utilize any backend languages such as php or python. Additionally, node.js is not necessary either!

All that is required is the EmailJS library, which is straightforward to use.

This article will demonstrate the steps to:

  • configure emailjs account
  • send email with the use of JS

In my project, I utilize both gulp and webpack to enable coding in the src file and serving it from the dist folder.

I will demonstrate the process of creating an email sender from scratch using a 5-step approach.

Step 1 – Create your form in HTML

To begin, it is essential to create an HTML form. It’s worth noting that there is no need to include validation attributes such as “required” or “max” because the preventDefault() function will be executed during the submit event, thereby overriding the functionality of those attributes.

In your form, it is crucial to include the

name

attribute for every input. These attributes will be required at a later stage.

My very simple form looks like that:

The file that needs to be rephrased is “src/html/index.html”.

  
class="form"> name='name' type="text" placeholder="Your name..." class="form__input" /> name='topic' type="text" placeholder="Topic..." class="form__input" />

Enter fullscreen mode
Exit fullscreen mode

Step 2 – Sign up to emailjs

To set up your emails, registration with the emailjs service is required. Rest assured, the website is highly intuitive and will not require a significant amount of your time.

Once you log in, you will need to specify your preferred email service, which is located in the

personal email service

zone. In my situation, I have chosen Gmail.

personal email service image

To begin, you must link your gmail account, which will serve as your email address for sending messages to you or your clients. For instance, if you connect your [email protected] account, all your future incoming emails will originate from this specific account. Therefore, you don’t need to request gmail to send emails on your behalf, as this fulfills your requirements perfectly.

Allowing sending emails image

Once you have linked your Gmail account, simply click on the

add service

button.
“””.

Step 3 – Create your mail template

Once you have successfully connected your Gmail account, you should now be on your dashboard, where you can begin creating your email template.

Navigate to the “email templates” card and click on

create a new template

. The user-friendly interface ensures a seamless template creation process. Customize the template by selecting a name and ID. For instance, I named mine “my-amazing-template”.

create template name and id image

Now, it is necessary for you to define the desired format of incoming emails. The values to be utilized are derived from the attribute

name

in the input. You must insert your variable within

{{{ }}}

placeholders.

Remember to enter your email address in the designated field (

To email

) on the right side. This is the address where your emails will be sent, specifically my business email.

This is a straightforward template that utilizes three variables extracted from my HTML form. Additionally, I have defined the subject of the incoming email.

create template content and body image

Step 4 – Save your API keys.

In this section, Emailjs provides authorization API keys for email sending. The ideal location to store these keys is within the config, referred to as

.env

. However, to avoid dealing with server configuration, I will save them in a separate file called

apikeys

and import them later.

  • Your USER_ID is located in the Account > API Keys.

    user id section image

  • And your TEMPLATE_ID is below the title of your template.

    template id section image

This is my sample configuration that relies on non-existent keys found in src/js/apikeys.js.

export default {
    USER_ID :'user_DPUd-rest-of-my-id',
    TEMPLATE_ID:'my_amazing_template'
}

Enter fullscreen mode
Exit fullscreen mode

Ensure that the APIKeys file is included in the .gitignore when deploying to GitHub.

Step 5 – Send email!

We are now approaching the final and crucial phase of the project, which involves utilizing JavaScript to send emails.

Initially, the emailjs package must be downloaded.


npm i emails-com

Next, proceed to your js file where you can import both your library and apikeys.


src/js/main.js

import emailjs from 'emailjs-com'
import apiKeys from './apikeys'

Enter fullscreen mode
Exit fullscreen mode

It is now the moment to create a function for sending emails in the main.js file located in the src/js directory.

const sendEmail = e => {
    e.preventDefault()
    emailjs
    .sendForm('gmail', apiKeys.TEMPLATE_ID, e.target, apiKeys.USER_ID)
    .then(
      result => {
        console.log(result.text)
      },
      error => {
        console.log(error.text)
      }
    )
}
Enter fullscreen mode
Exit fullscreen mode

The sendForm function is straightforward, as you can observe. It requires four parameters.

  • The location of your email’s ID can be found at
    serive id image
    .
  • The TEMPLATE_ID is retrieved from the apikey file.
  • the event object that is generated when your form is submitted
  • The USER_ID is obtained from the apikey file.

Finally, locate the form and attach the submit listener to it in the src/js/main.js file.

const form = document.querySelector('.form')
form.addEventListener('submit',sendEmail)

Enter fullscreen mode
Exit fullscreen mode

As previously stated, the attribute validation will fail due to the

preventDefault()

function. Consequently, it is necessary for you to handle the validation and clearing of inputs manually using JavaScript.

And that‘s all – let us test that.

I am completing the form on my page and submitting it.
filled email form image
I receive the email that was provided when the template was created.
email incoming image
email incoming image
Indeed, all the input values are correctly placed.

Conclusion

It is evident that sending emails in JS is not a difficult task. With the use of emailjs, you can easily send email messages. I am confident that your prospective clients will appreciate receiving emails from forms on their website.
I am here to assist you and my code for this article can be found at: https://github.com/Iwaniukooo11/email-sender.

Frequently Asked Questions