You can’t send an email from the front-end with JavaScript, or can you?

Send emails from the Front-end with EmailJS

Some time ago, I was writing a JavaScript app and wanted to implement a mail sending function, so I tried Google;from my search and research, I realized I can not exactly send a mail directly with JavaScript, but I found some useful solutions.

The first solution was using the ‘HTML5 emailto:’ attribute, but this solution had three cons, one is it leaves my email open to the public which makes it a potential spam bank (pun intended), the second problem with this solution is that it has to go through the mail client on the user’s system, which means it won’t work on systems which have no emailing app installed and the third was that mail subject and message is not customizable, and you can’t dynamically select the receiver of the mail because it can only be hard coded as so ‘emaito:john@dow.com’.

The second solution was to use nodemailer but that meant I would have to write a backend which I didn’t want to because the app is really small. SendGrid too provided a similar feature I think, but I never really understood the documentation so I bailed on SendGrid too.

Finally, I came across EmailJS and it had the exact features I wanted and the best part was it can be implemented on the Front-end with very few lines of JavaScript, Eureka!!!. I’ll share my configuration and implementation below because the EmailJS documentation can be quite confusing too for other noobs like me.

Configuring EmailJS

STEP 1: create an account on EmailJS and then navigate to Email Services page on the dashboard, click on ‘add services’, you should see a list of supported mail services, I chose Gmail but you can choose whichever works for you. If you decide to use Gmail, you have to ‘allow less secure apps’ in the Gmail settings for it to work as desired. Fill out the email service details and then send a test email to confirm if your EmailJS account has been successfully linked to the email service. You get 200 emails daily on the free plan, but you can go for an upgraded paid plan any time you like.

STEP 2: we move to creating email templates which are required for each type of email that needs to be sent with EmailJS. Go to the Email Templates page on your EmailJS dashboard and then click on “create new template”, you can choose a pre-designed template or design yours. Each template contains fields like email subject, body, to email, Reply to, etc.

Sample of an EmailJS template

STEP 3: we add dynamic variables to be used in our code, to the email templates; they are added by wrapping the variable with double or triple curly braces. For example: {{to}}, {{subject}}; but if you want the variable to be filled by html that is not escaped, we use triple curly braces as such {{{html}}}. This brings us to the end of the EmailJS configuration, now we move to the function implementation.

EmailJS Function Implementation

We have to connect to the EmailJS CDN server by pasting the following code snippets inside the <head> tag, just before </head> closing tag.

<head>
<script type="text/javascript" src=" https://cdn.emailjs.com/sdk/2.3.2/email.min.js"></script>
<script type="text/javascript">
(function (){
emailjs.init("user_User+IDgibberish");
})();
</script>
</head>

This snippet can be gotten from the installation tab on the dashboard, just click on installation, copy the snippet shown and paste into your <head> tag; it must be below your <link> tag, if you have one in the <head>. To confirm if your User ID is correct, click on your name at the top of the dashboard or on Account in the side panel, and then navigate to API keys, you’ll see your User ID and Access token.

Next thing is to define the template parameters and emailJS function in our index.js or whatEverYouNamedIt.js file. Let’s assume we have a button that we added an event listener to like so

button.addEventListener ('submit', () => {  let templateParams = {  to: user.email,  subject: 'Welcome to The Universe',  html: `  <h2>Welcome ${user.name} ${user.surname},</h2>  <p>There's no other Universe you'll rather inhabit</p>`}emailjs.send('default_service', 'emailjs_article', templateParams)  .then(function (response) {  console.log('SUCCESS!', response.status, response.text);  }, function (error) {  console.log('FAILED...', error);  });});

“let templateParams” is the declaration of the template parameters.

to, subject and html are the parameter variables that will be populated in your template. See the red arrows in image below.

arrows indicating dynamic variables

“to” represents the email of the recipient which will be dynamically populated with javascript.

“subject” simply means the subject of the mail you wish to send.

“html” is the body of the mail you wish to send; it has 3 curly braces around it “{{{html}}}”, unlike others which have just 2 in the template, this is because we don’t want the html tags to be escaped. If we’re sending plain text or we want the html tags escaped, we use {{message}} instead.

emailjs.send() is the method that sends the mail to the emailJS CDN. As you can see in the code above, it has three arguments; (‘default_service’, ‘emailjs_article’, templateParams).

‘default_service’ represents the email service you selected when you registered your EmailJS account.

‘emailjs_article’ is the template ID of the template in which the template parameters you defined will be populated.

arrow pointing at Template ID

‘templateParams’ is the template parameters you defined earlier.

The emailjs.send() method returns a promise which is logged in the console if the email was sent successfully or if the email sending failed.

This brings us to the end of this article/tutorial, you can drop your questions below and I’ll try as much as possible to answer them.

P.S. I should add that I’m not really sure this EmailJS approach is very safe because your User ID is exposed to the Universe in your markup.

P.S. This is my first ever JavaScript article so it might look a bit ugly, but please give plenty claps to encourage me 😄.

I love JS, JSON, PYTHON, CRON and PS.