How to send emails in Javascript (NodeJS)

JS SMTP email sending guide using HTML and NodeJS.

A programming language called JavaScript is utilized for both front-end and back-end development. This post will offer a shift in viewpoint from the server-side to the client-side by utilizing JS to send emails from an application with no back-end.

JavaScript email transmission

JavaScript code cannot send emails by itself since server sockets are not supported. A server-side language that communicates with the SMTP server is needed for this. For the server script to send emails from the browser in response to queries, JavaScript is also used.

Why you would want to use JS to send emails

Emails are often sent through the server-side of a standard app. A server setup utilizing back-end technology is required. The server side receives a request from the client-side and responds by creating an email and sending it to the SMTP server. Why then use JavaScript to send emails directly from the client side. Such a method is quite helpful for developing contact forms and other user interfaces for web apps since it enables email sending without requiring the user to reload the page they are currently viewing. Additionally, you don't need to play around with server programming. If your web application solely sends emails in response to contact forms, this is a compelling argument. You can choose from a few options below to enable client-side email sending in your app.

Mailto: for delivering form data,

You can program the browser to launch the default mail client to send an email directly through JS. Although it is not technically possible to send an email straight from a browser, the mailto: method can be used.

HTML example

See how the following piece of code functions:

<form action="mailto:you@yourdmainhere.com" method="post" enctype="text/plain" >
FirstName:<input type="text" name="FirstName">
Email:<input type="text" name="Email">
<input type="submit" name="submit" value="Submit">
</form>

You'll see the following when you open it in the browser:

gmail

Following the data submission, the browser launches the default mail client.

compose email

Although the mailto: method is a fairly simple implementation, it has the following specific drawbacks:

  • Given that the data is supplied in the form that the browser sends, you do not influence how the data is laid out.

  • Mailto: doesn't guard against spambots gathering your email address. A link might be built-in JS in the past to help with this. Nowadays, a growing number of bots use JS and do not solely rely on HTML produced by the server.

MailSlurp true email sending

A free package called SmtpJS can be used to send emails from JavaScript. To complete the task, an SMTP server and a few adjustments are required. Since mailslurp is a practical email testing solution, it serves as the server in this example. The procedure to follow is outlined below: Create an HTML file with the following script in it (for instance, test.html):

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

A button that will activate the JavaScript function should be created.

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

Create the JS function to use SmtpJS.com to send emails.

function sendEmail() {
Email.send({
    Host : "smtp.mailslurp.com",
    Username : "<mailslurp username>",
    Password : "<mailslurp 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)
);
}

You can include an array of email addresses in the To: attribute if you have numerous recipients. Send emails by running “test.html” in the browser.

The problem with the code example above is that the client-side script makes your login and password visible. If you use the SmtpJS encryption option, you can resolve this. After completing the necessary fields, click the box that says "Encrypt your SMTP credentials." Following that, select Generate security token, and use it in your JS function in place of the following SMTP server settings:

SecureToken : "<your generated token>"

An HTML email sample and an email with an attachment are shown below. This is how the email will appear in the recipient's inbox, thanks to mailslurp's GUI.

An example of HTML email coding:

<script src="https://smtpjs.com/v3/smtp.js"></script>
<input type="button" value="Send Email" onclick="sendEmail()">
<script>
function sendEmail() {
	Email.send({
    SecureToken : "<your generated token>",
    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("mail sent successfully")
    );
}
</script>

Sample of the code needed to send an email with attachments Use the Attachments property to send an email with an attachment as shown:

Sending without code

Without using any server code, mailslurp.com enables connecting email providers, creating email templates, and sending them from JavaScript. Choose a service to connect with and create an account. Both personal services like Gmail or Outlook and well-known transactional service choices like Amazon SES or Mailgun are offered. mailslurp is used in this illustration.

The built-in editor can be used to create email templates. There are many possibilities for creating material in the editor, along with additional helpful tools like auto-reply, reCAPTCHA verification, and others. Additionally, you must be familiar with the fundamentals of writing your HTML email template. Click Save after you're done. The fact that the standard email characteristics are concealed is one of mailslurp.com's key advantages. Since the recipient field is included in the template and cannot be changed using JS, you transmit the template that was previously set up. You must now install the mailslurp SDK. Npm can be used for this:

npm install mailslurp-com --save

Via browser

bower install mailslurp-com --save

You should insert the following code before the closing tag if you need to use mailslurp on your website:

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

Two techniques can be used to send the email itself:

  • mailslurp.send
  • mailslurp.sendForm.

mailslurp.send

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

mailslurp.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);
    });

mailslurp.sendForm

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

mailslurp.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);
    });

Let's send an email directly from the browser to see if mailslurp.com functions as expected. We have created a straightforward template and set up the mailslurp email service. Now, we must write the following code into an HTML file:

<script type="text/javascript"
        src="https://cdn.jsdelivr.net/npm/mailslurp-com@2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      mailslurp.init("<USER-ID>"); //Insert your User ID
   })();
</script>
<script>
	var templateParams = {
    name: 'Sender',
    notes: 'Test email'
};

mailslurp.send('<email-service-ID>', '<email-template-ID>', templateParams) //Insert your email service ID and email template ID
    .then(function(response) {
       console.log('SUCCESS!', response.status, response.text);
    }, function(error) {
       console.log('FAILED...', error);
    });
</script>

Try it out in your browser by opening the mailslurp Demo Inbox. It works!

However, there is a way to send emails without ever using a browser that is simpler and faster. After testing them, “mailslurp Email Delivery” enables you to rapidly authenticate your domain and send emails using SMTP or API.

To conclude

You can avoid dealing with server-side coding even if sending emails is a server-side function. Two practical options for streamlining your front-end and enabling email sending are:

  • MailSlurp

MailSlurp is superior since it conceals common email properties and lets you send any templates you've previously set up. While the mailto: approach is different, it too has its uses.

Related content

Java email library for SMTP and creating email addresses

MailSlurp Java SDK for sending and receive email and attachments on the JVM.

NodeJS MailSlurp SDK

Nodemailer alternatives to send and receieve email in code and tests

SMTP email application libraries

How to send email in CSharp, PHP, Ruby, Java, Python, and NodeJS using the SMTP protocol and MailSlurp mailservers.

Email for testing

Test email accounts for email testing. Alternatives to Mailinator, MailTrap, Mailosaur and more.

Email marketing campaign bulk email testing

Send bulk transactional emails with MailSlurp online or in code using CSharp, Node.js, Java, PHP and more.

Cold Emailing in Compliance with CAN-SPAM

Cold Emailing in Compliance with CAN-SPAM

Do's and Don'ts for multiple SPF records

Do's and Don'ts for multiple SPF records

Email Over Blockchain

Can emails be sent over blockchain? Well kind of! LedgerMail and other and at the cutting edge of decentralized email.

Explaining Cloud Email with Options to Think About

Explaining Cloud Email with Options to Think About

Fastest way to start a typescript project

Modern typescript tooling has come a long way. See how to setup a new project with TS-Node, TSC, and typeconfig.json.

Fetch error message javascript

Handle response exceptions with Fetch in Javascript

GraphQL API disposable email accounts

How to create real email addresses using GraphQL to send and receive emails in tests and frontend applications.

GraphQL Email API Tutorial

Did you know you can send and receive emails using GraphQL?

How to choose the right email design size (for various campaigns)

Email sizes can be instrumental to determine if your consumer will comprehend and engage with your content. While the template width (600 px) is typical, there are nuances to be mindful of. There are no hard and fast standards for email template height like design blocks.

How to Send an Email in Python

Send emails using SMTP mailer in Python. Detailed tutorial for sending mail in Python.

HTML Mailto Links Explained

HTML Mailto is uncomplicated to use. This link opens the default email client and adds a new notification maker. Pre-populated fields save time and prevent email bounces. This post will cover customizing mailto. We'll also discuss its viability in this decade. Come on.

Hugo responsive image srcsets

Serve responsive picture tags with custom render-image layout partial in Hugo static site generator.

How to send emails in Javascript (NodeJS)

JS SMTP email sending guide using HTML and NodeJS.

Mailinator alternative

Alternatives to Mailinator for test email accounts. Create real email addresses using MailSlurp

How to use Mailto links

Mailto links not working guide.

Manage Email Throttling Correctly!

Manage Email Throttling Correctly!

Maximum Email Size and How to Optimize It

Email sizes are fundamental for a few important reasons. One is security, and another is the performance of your email.

NodeMailer NPM Tutorial

Send and receive email using NodeMailer in Node JS.

How to send an email using Powershell (Windows and cross-platform)

Use Send-MailMessage in Windows Powershell to send emails using an SMTP server or MailSlurp's free email API.

Create custom print classes with Tailwind

Configure tailwind.config.js to create prefixed classes with a custom media query.

Test SMTP servers with Telnet

How to use Telnet to test the SMTP servers?

Transactional Email Services Compared

Sending emails is important for many applications. Top 10 transactional email services compared.

What Is Amazon Simple Storage Service (SES) - And How Can I Use It?

Amazon SES is an email service among virtual servers, AI apps, and libraries. Ideally, you can integrate your email system with your program hosted on Amazon.

What is DKIM Email

How to setup and configure DKIM signatures with the sender policy framework (SPF)

Grab all details about an SMTP Port

What are common SMTP mail server ports and how do you find them?

Which SMTP Port Should I Use?

Picking the right port for SMTP mailservers

CypressJS Example

Test email sign-up. password verification and more with Cypress JS and MailSlurp.

CypressJS Email Testing

Use real email accounts in CypressJS to test user sign-up, email verification, and more.

Jest, Puppeteer

Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.

Webdriver, JS, WDIO

Test email related processes like sign-up and verification using WDIO WebDriver and MailSlurp.

TestCafe end-to-end MFA testing for user sign-up and email verification

End-to-end testing with MailSlurp, NodeJS, and TestCafe.

Avoiding email spam filters

How to send emails that don't trigger a spam warning.

Base64 file uploads

How to encode files as Base 64 encoded strings in several languages

BCC and CC in SMTP emails

BCC and CC in SMTP emails

BCC For Email: What It Means And When To Use It

What is BCC email field (blind carbon copy) and how does it differ to CC?

What Is The Best SMTP Port To Use?

MailServers use TCP ports to transmit emails. Picking the right port between 25 vs 2555, 465 vs 587 in SMTP is easy with this guide.

How to configure Mail desktop clients with MailSlurp

How to setup MailSlurp with Outlook, Gmail, Thunderbird, Mail app and more.

CSharp Email Tutorial

SMTP mailserver testing and usage in CSharp using

Send email with CSharp using SMTP Client and MailSlurp

Create a custom SMTP client and access MailSlurp inboxes from CSharp/DotNET.

Deno Email Apis

Send and receive emails in Deno JS. Use APIs in Deno with MailSlurp.

DMARC – All Facts that you should know

DMARC – All Facts that you should know

Email read (opened seen settings)

How to control the seen or read settings for an email using MailSlurp.

Email size limits

Email size limits

The Fundamentals Of Email Subdomains

How to manage email subdomain custom mailboxes using SMTP/IMAP mailserver settings.

GraphQL Email API

Fetch and read emails with GraphQL inboxes using MailSlurp email API.

Testing OTP password link username and password for 2 factor authentication (2FA)

Testing OTP password link username and password for 2 factor authentication (2FA)

A guide to PHP Mailer

A guide to PHP Mailer

SMTP IMAP Settings

How to access MailSlurp email accounts using IMAP and SMTP servers

MailSlurp NodeMailer SMTP Usage

Use SMTP nodemailer with MailSlurp disposable email addresses

SMTP Relay for outbound smtp servers

How to use SMTP relay to address spam and security issues that affect outbound mail servers.

SMTP vs HTTP MailSlurp inboxes

The difference between HTTP and SMTP inboxes and domains in MailSlurp.

Testing email with Cypress test email accounts

Test email accounts for CypressJS. End-to-end testing with real email addresses using MailSlurp Cypress plugin.

What are SMTP ports

What are SMTP ports

CSharp send SMTP email

How to use CSharp SMTP client to send email with MailSlurp mail server

Send SMTP email with Java

How to use Java SMTP client to send email with MailSlurp mail server on the JDK

Send emails in NodeJS using SMTP

How to use Javascript SMTP client (or Nodemailer) to send email with MailSlurp mail server

Send SMTP emails with PHP

Use PHPMailer to send emails with SMTP and MailSlurp

Send SMTP email with Python (using SMTPLib)

How to send emails with Python's built-in SMTP client and MailSlurp mail servers.

Ruby send SMTP email

How to use Ruby SMTP client to send email with the MailSlurp mail servers

Email internationalization and i18n localization

Email internationalization and i18n localization

Testing Email with Cypress JS and MailSlurp

Email testing with Cypress JS

Ready to dive in?Start building email applications today.