SMTP.js – Send Email without a Server from the Browser
Tags: react, javascript, programming, beginners
Published: 2023-10-30 03:55:50

<p data-pm-slice="1 3 []">Sending email directly from the browser without needing a backend server is now possible using SMTP.js. SMTP.js is a JavaScript SMTP client library that allows you to send mail through client-side JavaScript by wrapping the SMTP protocol.</p>
In this post, we'll cover how to get started with SMTP.js, its features, use cases, and some frequently asked questions on using a JavaScript SMTP library.
<blockquote><em>Follow this guide to learn </em><a class="attrlink" href="https://blog.learnhub.africa/2023/08/29/how-to-scrap-linkedin-company-data-using-voyager-api/" target="_blank" rel="noopener noreferrer nofollow"><em>How to Scrap LinkedIn Company Data using Voyager Api</em></a><em>.</em></blockquote>
<h4>Why Send Email from the Browser?</h4>
Here are some reasons you may want to send email directly from the browser without a backend server:
<ul>
 	<li><strong>No server dependencies</strong> - You don't need to rely on a server language like PHP or Node.js to send mail. The entire email process can be handled client-side.</li>
 	<li><strong>Faster prototyping</strong> - You can quickly build and iterate on a contact form or newsletter subscription without needing backend code.</li>
 	<li><strong>Reduced server load</strong> - Sending mail client-side reduces the load on your servers.</li>
 	<li><strong>Increased privacy</strong> - Email contents stay isolated in the browser and aren't sent to your servers.</li>
 	<li><strong>Offline functionality</strong> - Emails can still be drafted and sent when offline or on poor connections. They will queue and send when a connection is re-established.</li>
</ul>
<h4>Limitations of Client-Side Email</h4>
There are some limitations to keep in mind:
<ul>
 	<li><strong>No server-side templates</strong> - You lose the ability to leverage templating engines like Pug or Handlebars. HTML email needs to be crafted client-side.</li>
 	<li><strong>No server-side storage</strong> - You won't have a server log of sent mail. Client-side storage like IndexedDB can be used instead.</li>
 	<li><strong>Spam prevention</strong> - Special care must be taken to prevent spam and abuse without server-side systems like CAPTCHA.</li>
 	<li><strong>Email deliverability</strong> - Reputation management is harder without consistent IP addresses and server-side software.</li>
</ul>
So, while SMTP.js removes backend dependencies, some use cases still lend themselves better to server-side email. But for many front-end-focused, privacy-centric, or offline-first applications, SMTP.js can be a great fit.
<blockquote><a class="attrlink" href="https://blog.learnhub.africa/2023/10/29/linkedin-voyager-api-the-ultimate-developers-guide/" target="_blank" rel="noopener noreferrer nofollow"><em>LinkedIn Voyager API: The Ultimate Developer’s Guide</em></a></blockquote>
<h4>Getting Started with SMTP.js</h4>
SMTP.js can be installed via npm:

<code>npm install smtp.js</code>

Or included directly in the browser from a CDN like unpkg:

<code>&lt;script src="</code><a style="pointer-events: none;" href="https://unpkg.com/smtp.js/dist/smtp.min.js&quot;&gt;&lt;/script&gt;" target="_blank" rel="noopener noreferrer nofollow"><code>https://unpkg.com/smtp.js/dist/smtp.min.js"&gt;&lt;/script&gt;</code></a>

To send a simple test email:
```javascript
import smtp from 'smtp.js';


const email = {

  from: 'sender@example.com',
  to: 'recipient@example.com',
  subject: 'Test email',
  text: 'This is a test email sent from the browser'

}


smtp.sendMail(email)
  .then(info =&gt; console.log(info))
  .catch(err =&gt; console.error(err)) 
```
We provide SMTP credentials and call smtp.sendMail() with the email object containing from, to, subject, and text fields.

The promise resolves with info about the message or rejects any errors.
<h4>SMTP Provider Credentials</h4>
To send real email, SMTP credentials need to be supplied:
```javascript
const credentials = {
  host: 'smtp.example.com',
  port: 465,
  secure: true, 
  auth: {
    user: 'username',
    pass: 'password'
  }
}
smtp.connect(credentials)
  .then(info =&gt; {
    // connected, credentials OK 
  })
```
Any SMTP provider can be used, like Gmail, Outlook, or a custom server.

Gmail would look something like:
```javascript">const credentials = {
  host: 'smtp.gmail.com',
  port: 465,
  secure: true,
  auth: {
    user: 'myaccount@gmail.com',
    pass: 'mypassword'
  }
}
```
Now, credentials are supplied to smtp.connect() before sending mail.
<h4>Sending the Message</h4>
With credentials configured, sending an email follows the same pattern:
```javascript">const email = {

  // sender/recipient

  from: 'sender@example.com',
  to: 'recipient@example.com',


  // email content  

  subject: 'Test email',
  text: 'Email content here' 

}


smtp

  .connect(credentials)
  .then(() =&gt; smtp.sendMail(email))
  .then(info =&gt; console.log('Email sent!'))
  .catch(err =&gt; console.error(err))
```
The message object can also take HTML email content:
```javascript
const email = {
  from: 'sender@example.com',
  to: 'recipient@example.com',
  subject: 'HTML email',
  html: '&lt;p&gt;This is an &lt;strong&gt;HTML email&lt;/strong&gt;&lt;/p&gt;'
}
```
That covers the basics of sending email with SMTP.js! Next we'll look at some more advanced features.
<h4>SMTP.js Features</h4>
SMTP.js supports several helpful features when sending mail:
<ul>
 	<li><strong>Multiple Recipients</strong></li>
</ul>
To send to multiple recipients, pass an array of addresses to:
```javascript
const email = {
  to: [
    'recipient1@example.com',
    'recipient2@example.com'
  ]
}
```
CC and BCC fields are also supported:
```javascript
const email = {
  to: 'main@example.com',
  cc: 'cc@example.com',
  bcc: 'bcc@example.com'
}
```
<ul>
 	<li><strong>Attachments</strong></li>
</ul>
To attach files, pass an array of attachments:
```javascript
const email = {
  attachments: [
    {filename: 'report.pdf', content: pdfBuffer}
  ] 
}
```
The content can be a Buffer, ArrayBuffer, Stream, or URL.
<ul>
 	<li><strong>Custom Headers</strong></li>
</ul>
Additional headers can be added:
```javascript
const email = {
  headers: {
    'X-Custom-Header': 'value'  
  }
}
```
<ul>
 	<li><strong>Email Queue</strong></li>
</ul>
To send multiple emails, an internal queue is used:
```javascript
// add emails to queue
smtp.addMailToQueue(email1);
smtp.addMailToQueue(email2);


// connect and send entire queue
smtp.connect(credentials)
  .then(() =&gt; smtp.flushQueue())
  .catch(err =&gt; console.error(err));
```
This allows sending a batch of emails efficiently.
<ul>
 	<li><strong>Custom SMTP Server</strong></li>
</ul>
Instead of a major provider, you can connect to a custom SMTP server:
```javascript
const credentials = {
  host: 'mail.yourdomain.com',
  port: 587,
  secure: false,
  auth: {
    user: 'username',
    pass: 'password'    
  }
}
```
Use any self-hosted SMTP server like Postfix, Sendmail, or Exchange.

This covers the main features of SMTP.js! Next we'll look at some good use cases for sending email from the browser.
<h4>When to Use SMTP.js</h4>
Several types of applications lend themselves well to using SMTP.js for client-side email:
<ul>
 	<li><strong>Contact Forms</strong></li>
</ul>
A common use case is browser-based contact forms:
```javascript
const form = document.querySelector('#contact-form');


form.addEventListener('submit', event =&gt; {
  event.preventDefault();
  const email = {
    to: 'contact@example.com',
    subject: form.subject.value,
    text: form.message.value
  }

  smtp.sendMail(email)
    .then(() =&gt; form.reset())
    .catch(err =&gt; console.error(err))
});
```
No server code is needed!
<ul>
 	<li><strong>Newsletter Signup</strong></li>
</ul>
For a newsletter signup form, save the email to IndexedDB and queue the confirmation:
```javascript
form.addEventListener('submit', event =&gt; {
  event.preventDefault();
  const email = form.email.value;
  db.users.add({email});
  const confirmEmail = {
    to: email,
    subject: 'Please confirm signup',
    text: 'Click here to confirm: https://...'
  }
  smtp.addMailToQueue(confirmEmail);
  smtp.flushQueue();
})
```
<ul>
 	<li><strong>Online Email Client</strong></li>
</ul>
SMTP.js allows building a web-based email client or webmail system without servers.

Messages stay local using IndexedDB or other browser storage for the mail client.
<ul>
 	<li><strong>CRM/Support Platforms</strong></li>
</ul>
In customer management apps, support agents can respond to tickets directly from the browser:
```javascript
agentForm.addEventListener('submit', event =&gt; {
  event.preventDefault();
  const {recipient, body} = form;
  smtp.sendMail({
    to: recipient,
    text: body
  });
});
```
Again, no server-side code is needed for sending responses.
<ul>
 	<li><strong>Offline Functionality</strong></li>
</ul>
For offline-first web apps, emails can be queued when offline and sent when a connection is

re-established:
```javascript
// detect connection state

const isOnline = navigator.onLine;

// queue message

smtp.addMailToQueue(email);

if(isOnline) {

  smtp.flushQueue();

} else {

  window.addEventListener('online', () =&gt; {

    smtp.flushQueue();

  });

}
```
So SMTP.js enables email functionality even without a network.

These are just a few examples of when sending mail directly from the client can be useful.
<h2>Common Questions</h2>
Here are answers to some frequently asked questions about using SMTP.js:
<h2>How does SMTP.js work without a server?</h2>
SMTP.js directly speaks the SMTP protocol to send mail. It is a client-side SMTP "server" connecting to real external servers. All the code is contained in the browser.
<h2>Is it secure to send email via client-side code?</h2>
SMTP.js is as secure as SMTP itself. All connections use TLS encryption, and credentials are not exposed client-side. The email contents and data stay local to the browser and JavaScript environment.
<h2>What is the advantage of a server-side solution?</h2>
It depends on the use case, but the advantages include no server dependencies, increased privacy, offline support, and reduced server load for things like contact forms.
<h2>What are the limitations?</h2>
Limitations include a lack of server-side templates, no central server log of sent mail, and reduced deliverability protections. Complex workflows involving mail merge and sending high volumes of email work better with a server.
<h2>How does email get delivered without a static IP address?</h2>
Services like Mailgun provide an SMTP API gateway with a consistent sending IP address and domain while masking the underlying client IPs. This helps improve deliverability.
<h2>Does SMTP.js work for sending bulk email?</h2>
SMTP.js can technically send bulk volumes, but server-side solutions are better suited for large mailing lists and newsletter campaigns. SMTP.js is better optimized for one-off transactional email.
<h2>Can SMTP.js connect to any SMTP service?</h2>
Yes, SMTP.js can connect to any standard SMTP provider or custom SMTP server with the proper credentials configured. Popular choices include Gmail, Mailgun, SparkPost, Amazon SES, or a self-hosted mail server.

Hopefully, this gives you a better understanding of how to use SMTP.js to send email directly from the browser! Let me know if you have any other questions.

If you find this article thrilling, discover extra thrilling posts like this on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write a lot of tech-related topics from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>. Take a look at <a class="attrlink" href="https://blog.learnhub.africa/2023/02/16/how-to-build-offline-web-applications/" target="_blank" rel="noopener noreferrer nofollow">How to Build Offline Web Applications. </a>
<h2><strong>Resource</strong></h2>
<ul>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/01/18/how-to-send-an-email-in-node-js-using-nodemailer/" target="_blank" rel="noopener noreferrer nofollow">How to send an email in node.js using nodemailer</a></li>
 	<li><a class="attrlink" href="https://www.w3schools.com/js/js_arrays.asp" target="_blank" rel="noopener noreferrer nofollow">Javascript Array method</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/09/20-best-javascript-frameworks-for-2023/" target="_blank" rel="noopener noreferrer nofollow">20 Best React JavaScript Frameworks For 2023</a></li>
</ul>