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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...