Using EmailJS: An Easy Way to Send Emails With JavaScript + HTML
Hey there! So, I recently stumbled upon this awesome tool called EmailJS, and I've got to say, I love it! It's like magic for sending emails directly from your JavaScript code without needing a backend. in essence, if you need to integrate email functionality quickly and don't want to manage a server, EmailJS is a good choice.
EmailJS Picture
But let me give you a heads-up: while EmailJS is fantastic for quick and simple forms, I don't think it’s something you'd want to use for sending super-sensitive information, because you rely on an external service, which may introduce concerns about security and data privacy. Think of it like sending postcards — fun and easy, but maybe not the best choice for your deepest secrets.
Now, let's dive into how to set up and use EmailJS for those less sensitive, but still awesome, email needs.
Step 1: Sign In or Sign Up for EmailJS
1. Visit EmailJS: Head over to the EmailJS website.
EmailJS Picture
2. Create an Account: Sign in if you have created an account or sign up for a free account. It’s super quick!
EmailJS Picture
Step 2: Create an Email Service
1. Sign in: Sign in to your EmailJS account.
EmailJS Picture
2. Navigate to Email Services: Click the Email Services section to add a new service. I have a few email services created earlier that you do not need to worry about.
EmailJS Picture
3. Add New Service: Click on Add new service, pick your favorite email provider (Gmail, Yahoo, Outlook — they're all there, however, I recommend Gmail), and click Connect Account. This will connect your email provider and assign you a Service ID.
EmailJS Picture
Step 3: Create an Email Template
1. Navigate to Email Templates: Go to the Email Templates section.
EmailJS Picture
2. Create a New Template: Click on Create New template.
3. Design Your Template: Customize the email template with placeholders for dynamic content and hit save. Something like this:
EmailJS Picture
Step 4: Create and Style the HTML Form
Create a contact form and style it as desired in your preferred code editor. I used VS Code and styled it so that it's nicely centered on the page. Here's how you can do it:
1. Create a contact form in a new file emaiJS.html
EmailJS Picture
2. Add some CSS styles
EmailJS Picture
EmailJS Picture
Explanation of some styles:
body styles: Centers the form on the page using Flexbox.
.form-container styles: Add padding, a border radius, and a shadow to make the form look nice and polished.
input, text-area: Ensures all form fields are full-width and styled uniformly.
button: Adds a background color and hover effect to make the button look clickable.
3. Run Live Server you should get something like this:
EmailJS Picture
Step 5: Add the EmailJS CDN
Next, let's add the EmailJS CDN to your project to enable the email-sending functionality.
1. Click Docs in the top right corner:
EmailJS Picture
2. Navigate to installation, copy the Browser script tag, and add it inside the <head> section of our emailJS.html
EmailJS Picture
EmailJS Picture
3. Replace “YOUR_PUBLIC_KEY” with your EmailJS public key, which you can find in the EmailJS dashboard under Account.
EmailJS Picture
Step 6: Implement the JavaScript Function
1. Let's implement the JavaScript function to send the email using EmailJS.
EmailJS Picture
Line-by-Line Explanation:
function sendEmail() { : This line defines a new function called sendEmail. This function will be called when the form is submitted.
const messageParams() { : Here, i declared a constant variable messageParams that will hold an object containing the values from the form fields.
name: document.getElementById('name').value, : This line accesses the input field's value with the id name in the form and assigns it to the name property of the messageParams object.
email: document.getElementById('email').value, : Similarly, this line accesses the input field's value with the id email and assigns it to the email property of the messageParams object.
message: document.getElementById('message').value, : Also, this line accesses the input field's value with the id message and assigns it to the message property of the messageParams object.
}; : This closes the messageParams object definition.
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', messageParams): This line calls the send method from the EmailJS SDK. It sends an email using the specified service ID (YOUR_SERVICE_ID) and template ID (YOUR_TEMPLATE_ID), along with the parameters (messageParams) defined earlier. Note that you have to replace YOUR_SERVICE_ID with the service ID that was assigned to you in step 2.3 and YOUR_TEMPLATE_ID with your actual template ID from EmailJS. You can get your template ID by hitting the email template settings in step 3.3.
.then(function (response) { : This starts a promise chain. If the send method succeeds, the function inside the then block is executed.
console.log('success!', response.status, response.text); : If the email is sent successfully, this line logs a success message to the console along with the response status and text.
document.getElementById('form').reset(); : This line resets the form fields to their default values, clearing the form.
alert('Email sent successfully!'); : This line displays an alert box to the user indicating that the email was sent successfully.
}, function (error) { : This starts the second part of the promise chain. If the send method fails, the function inside the error block is executed.
console.log('FAILED…', error); : If there is an error sending the email, this line logs a failure message to the console along with the error object.
}); : This closes the send method call and the promise chain.
} : This closes the sendEmail function definition.
2. Call the sendEmail function directly from the onsubmit attribute of the form tag
Now, you should have something like this:
EmailJS Picture
Note that the return false statement in the form submission event handler is used to prevent the default form submission behavior. This means that when the form is submitted, the browser will not try to send the form data to the server or reload the page. Instead, the form's submit event will be handled entirely by JavaScript.
Step 7: Test Your Setup
1. Run Your HTML: Open your emailJS HTML file with a live server in a web browser or press ALT+L and ALT+O simultaneously to do the same in VS code
2. Fill Out the Form: Enter details into the form and click Send.
EmailJS Picture
3. Check for Confirmation: Verify that the email is sent successfully with a pop up message Email sent successfully!.
EmailJS Picture
EmailJS Picture
And there you have it! With EmailJS, sending emails from your website with JavaScript and HTML is as easy as pie — no backend required. For little forms that don't include sensitive info, EmailJS is quick and easy to integrate.
But for those private messages (you know, the ones you don't want to accidentally send to the wrong person or, worse, leak to a third party), you're better off using Node.js, Express, and NodeMailer or any other backend you're comfortable with, which operates within your server environment.
Keep coding, keep smiling, and keep doing what you love!
Written by Yusuf Mustapha Opeyemi. July 22, 2024.