DEV Community

Cover image for Send e-mails directly from front-end with JavaScript 💥💥
Mateusz Iwaniuk
Mateusz Iwaniuk

Posted on

Send e-mails directly from front-end with JavaScript 💥💥

My code from project is available here: https://github.com/Iwaniukooo11/email-sender

Nowadays, when creating even basic websites, programmers are obliged 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 are many 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 by sending email?

Yes, it‘s definitely the best option, which is the most user-friendly. Your clients are going to be 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>
Enter fullscreen mode Exit fullscreen mode

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 user-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'
}

Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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)
      }
    )
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.
I believe that I could help you. My code from this article is located here: https://github.com/Iwaniukooo11/email-sender

Top comments (15)

Collapse
 
mikenikles profile image
Mike

I'm curious to understand the security of this solution. If I visit your site, could I not take your USER_ID and send emails on your behalf?

Collapse
 
iwaniukooo11 profile image
Mateusz Iwaniuk

Hi, at first I want to thank you all for taking part in discussion.
In my project I have used webpack and gulp thanks to what finished JS code is bundled and minified, which makes searching IDs harder.
Problems with visible of API is not a problem of this package, but of the entire front-end. Even when you want to fetch f.e Pizza API, you might be obliged to pass your private key, which later will be visible in dev tools.
In my article I have bundled and minified code which is in seperated file. It is still more safer than keeping everything in HTML file, what was shown on this documentation part

Collapse
 
veebuv profile image
Vaibhav Namburi

I believe a solution like this would work due to domain restrictions. I.e you can take the keys and user ID, but can only send/activate the service if the domain matches

Collapse
 
franky47 profile image
François Best • Edited

You could probably use that USER_ID from the devtools console of the appropriate domain and send whatever you want, impersonating the domain owner.

Edit: the FAQ of the service indicates you can only send predefined template emails, but template variable injection could be abused.

Thread Thread
 
mikenikles profile image
Mike

Yeah that's somewhat a relief 😅. As a bad actor, I could still send thousands of messages, potentially causing increased cost or worse, the email account getting blocked.

This service seems convenient at first, but with today's serverless solutions it's worth building a backend solution that is properly secured.

Thread Thread
 
xr0master profile image
Sergey Khomushin

There is no way you can solve this problem by creating your solution. As a bad guy, I can just as well call your API for your form.

Collapse
 
patricnox profile image
PatricNox

Very true. An OAuth token should always be used in these API scenarios which does more than only being used for a getter.

Collapse
 
xr0master profile image
Sergey Khomushin

What prevents from calling the API using an access token (from OAuth)?

Collapse
 
aajahid profile image
Abdullah Al Jahid

I think your post title is misleading. What you explained is exactly what everyone is doing. Sending a request from frontend to backend ( in your case a 3rd party service provider ).

Collapse
 
iwaniukooo11 profile image
Mateusz Iwaniuk • Edited

Hi Abdullah,
Someone earlier has mentioned that, let me show you my point of view
This article is intended for developers, who don't want to use any back-end technologies. Of course - it is true that EmailJS uses its 3rd party provider but you, as a programmer, don't have to take care about that. The main point is that you don't have to use node.js or php, but you can send email using simple package on your front-end side

Collapse
 
marwanm_dev profile image
Marwan mostafa

That's Cool, Another method is by using Formspree either way In the past I wasn't expecting its simplicity.

Collapse
 
iwaniukooo11 profile image
Mateusz Iwaniuk • Edited

Well, that's right, but this article is intended for developers, who don't want to use any back-end technologies. Of course - it is true that EmailJS uses back-end on its side, but you, as a programmer, don't have to take care about that

Collapse
 
xr0master profile image
Sergey Khomushin

Does the end user/developer really matter how it happens?

Collapse
 
kirkovg profile image
Gjorgji Kirkov

Hi Mateusz, it seems that the link to the repo is broken :/

Collapse
 
iwaniukooo11 profile image
Mateusz Iwaniuk

I'm sorry, it is fixed now 😅