Skip to main content

Send e-mails directly from front-end with JavaScript

Nowadays, when creating even basic websites, programmers are obligated to use modern features and technologies. Even such basic project as creating simple portfolio for your friend may involve some problems, like receiving data from contact form.
There is plenty of ways to read those data. You can connect your form with the database (f.e Firebase), and then read incoming messages from it. Well, it is an option, but I assume that it might be troublesome for your not-tech client.

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

Yes, it‘s definitely the best option, which is the most user-friendly. Your clients will be very much happier, when they will receive incoming messages without using the database. But here comes the issue – How to implement that? Well, you may think that you need to use kind of back-end language.
Me and my guys waiting for you to send email
Not at all! You don‘t have to use any of backend languages like php or python. Furthermore, you don‘t need even node.js!
Everything you need is a simple EmailJS library
In this article I will show you how to:
  • configure emailjs account
  • send email with the use of JS
Note, that in my project I have used gulp and webpack, thanks to what I write code in src file and serve it from dist.
I will show you in 5 steps, how to build an email sender from scratch.

Step 1 – Create your form in HTML

The very first thing that is required is of course creating a HTML form. Note, that you don‘t have to put validate attributes like required or max, because later on, the preventDefault() function will be run on your submit event and it will cancel working those attributes.
The most important thing in your form is to put the name attribute for each of inputs. They will be necessary later.
My very simple form looks like that:
src/html/index.html
  <form class="form">
        <input name='name' type="text" placeholder="Your name..." class="form__input" />
        <input name='topic' type="text" placeholder="Topic..." class="form__input"  />
        <textarea name='message' type="text" placeholder="Your Message..." class="form__input"  ></textarea>

        <input type="submit" value="send" class="form__input form__input--button">
    </form>

Step 2 – Sign up to emailjs

To configure your emails, you have to sign up to emailjs service. Don‘t worry – working with this website is very friendly and you won‘t spend lot of time on it.
After login, you will be asked about your email service.It is placed in the personal email service zone. In my case, I have picked the gmail.
personal email service image
Then, you will have to connect your gmail account. It will be your email, which will be used to sending emails to you/your client. So for example, if you connect your xyz@gmail.com account, your future incoming emails will be sent from exactly this account. So don‘t worry about asking gmail for sending emails on your behalf – this is exactly what you need!
Allowing sending emails image
After connecting gmail account, click add service button.

Step 3 – Create your mail template

If you have connected your gmail account successfully, you should be now in your dashboard. And this is the time for creating your email template.
Go to the email templates card and click create a new template. The interface is very friendly, so you won‘t have any problems with creating it.
You can select name and ID of your template. I have called it ,,my-amazing-template".
create template name and id image
You have to now specify, how incoming email should look like.
The values that will be used, are coming from name attribute in input. You have insert your variable into {{{ }}} signs.
Don‘t forget to place an email address in To email section (on the right side). It as an address, to which your emails will be sent. In this case - this is my business email.
This is my simple template which uses each of 3 variables, that come from my HTML form. I have also specified a subject of incoming email.
create template content and body image

Step 4 – Save your API keys.

Well, there is nothing special in this part. Emailjs shares authorization API keys that will be used during sending email. Of course, the best place to put these keys is .env config. But because of the fact, that I am working with simple static files and I don‘t want to work with server configuration, I will save them in the apikeys file and later will import them.
  • 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 example config based on not-existing keys
src/js/apikeys.js
export default {
    USER_ID :'user_DPUd-rest-of-my-id',
    TEMPLATE_ID:'my_amazing_template'
}

DO NOT FORGET TO ADD APIKEYS FILE TO .GITIGNORE WHEN DEPLOYING TO GITHUB

Step 5 – Send email!

It‘s time for the last and most important part of the project. Now we have to send email with the use of javascript.
At first, you have to download emailjs package.
npm i emails-com
After that, go to your js file and import your library and apikeys.
src/js/main.js
import emailjs from 'emailjs-com'
import apiKeys from './apikeys'
Now it‘s time to write a sending email function.
src/js/main.js
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)
      }
    )
}
It is so simple;
As you could see, sendForm function takes 4 parametres:
  • id of your email, which is located here:serive id image
  • TEMPLATE_ID coming from your apikey file,
  • event object from your form submitting
  • USER_ID coming from your apikey file,
And at the end, find the form and add the submit listener.
src/js/main.js
const form = document.querySelector('.form')
form.addEventListener('submit',sendEmail)
As i mentioned earlier, because of preventDefault() function, your attribute validation will not work. You have to do validation and clearing inputs on your own with the use of JS.
And that‘s all – let us test that.
I‘m filling up the form on my page and sending it.
filled email form image
I receive my email, which was passed during the template creating.
email incoming image
email incoming image
And indeed, all values coming from inputs are in the right place.

Conclusion

As could be seen, sending emails in JS is not so hard thing. With the emailjs you can send email messages in the easy way. I‘m sure that your future clients will be happy about incoming mails from forms located on their webpage.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...