DEV Community

AlexandraMT
AlexandraMT

Posted on

How to send Emails with JavaScript

JavaScript is a programming language that you can use for both front-end and back-end development. You can’t send emails using JavaScript code alone due to lack of support for server sockets. For this, you need a server-side language that talks to the SMTP server. You can use JS in conjunction with a server script that will send emails from the browser based on your requests. This is the value we’re going to introduce below.

So, let’s figure out how you can use JS to send emails from the app that has no back-end.

If you want to read a full article, check it out on the Mailtrap’s blog: Sending Emails with JavaScript

SmtpJS.com – true email sending from JavaScript

SmtpJS is a free library you can use for sending emails from JavaScript. All you need is an SMTP server and a few manipulations to get things done. We’ll use Mailtrap as the server because it is an actionable solution for email testing. Below is the flow you should follow:

  • Create an HTML file (for example, test.html) with the following script:

<script src="https://smtpjs.com/v3/smtp.js">
</script>

  • Create a button that will trigger the JavaScript function

<input type="button" value="Send Email" onclick="sendEmail()">

  • Write the JS function to send emails via SmtpJS.com.

function sendEmail() {
Email.send({
Host : "smtp.mailtrap.io",
Username : "<Mailtrap username>",
Password : "<Mailtrap password>",
To : 'recipient@example.com',
From : "sender@example.com",
Subject : "Test email",
Body : "<html><h2>Header</h2><strong>Bold text</strong><br></br><em>Italic</em></html>"
}).then(
message => alert(message)
);
}

If you have multiple recipients, you can specify an array of email addresses in the To: property.

  • Run test.html in the browser and send your email

Image description

The drawback with the code sample above is that your username and password are visible in the client-side script. This can be fixed if you utilize the encryption option provided by SmtpJS. Click the Encrypt your SMTP credentials button and fill in the required fields.

Image description

After that, press Generate security token and use it then in your JS function instead of SMTP server settings like the following:

SecureToken : "<your generated token>"

EmailJS

EmailJS.com allows you to connect your email service, build an email template and send it from JavaScript without any server code. Let’s check out the scope.

  • Create an account and choose an email service to connect with. There are the popular transactional services options available, such as Amazon SES or Mailgun, as well as personal services like Gmail or Outlook. You can also add a custom SMTP server. That’s what we’re going to do since we use Mailtrap.

Image description

  • Create an email template using the built-in editor. The editor provides plenty of options for content building and other useful features, such as auto-reply, reCAPTCHA verification, and more. It’s also necessary to understand the basics of coding your own HTML email template. For this, read our Guide on How to Build HTML Email. Once this is done, click Save.

One of the major benefits of EmailJS.com is that the typical email attributes are hidden. The template includes the recipient field and it cannot be overridden from JS, so you send the template you have configured previously.

  • Now you need to install EmailJS SDK. This can be done with npm: npm install emailjs-com --save or bower bower install emailjs-com --save

If you need to use EmailJS on your website, paste the following code before closing tag:

<script type="text/javascript"
   src="https://cdn.jsdelivr.net/npm/emailjs-com@2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      emailjs.init("YOUR_USER_ID"); //use your USER ID
   })();
</script>

Enter fullscreen mode Exit fullscreen mode
  • The actual email sending can be carried out via two methods: emailjs.send or emailjs.sendForm. Here are the code examples for both of them:

emailjs.send

var templateParams = {
    name: 'James',
    notes: 'Check this out!'
};

emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams) //use your Service ID and Template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });
Enter fullscreen mode Exit fullscreen mode

emailjs.sendForm

var templateParams = {
    name: 'James',
    notes: 'Check this out!'
};

emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams) //use your Service ID and Template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });
Enter fullscreen mode Exit fullscreen mode

Although sending emails is a server-side thing, you can refrain from dealing with server-side coding. SmtpJS and EmailJS are two actionable solutions to streamline your front-end and make it able to send emails. EmailJS is better because it hides typical email attributes and you are able to send whatever templates you have configured before. You can also use the mailto method, which is different but can still be useful in some cases. Try Mailtrap to test what better works for you!

Learn more about mailto and read the full article: Sending Emails with JavaScript

Consider to create an account at Mailtrap.io and try the described flow by your own!

Top comments (1)

Collapse
 
xr0master profile image
Sergey Khomushin • Edited

Thanks for the detailed article! We also use Mailtrap.io, and we especially like the analysis of email design.
Can I make a few clarifications about EmailJS? The emailjs.sendForm must have an instance form or a css selector as the third parameter. The emailjs-com package was marked as deprecated a year ago, please use @emailjs/browser.