CodeNewbie 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>

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

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

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 (6)

Collapse
 
gastonarchi451 profile image
GastonArchi451

Thanks for this guide! But sometimes there are more realistic tasks with ready-made shipments or transfers. In this case, I advise outlooktransfer.com/products/thund... with thunderbird to outlook transfer, since with this possibility you will not lose anything and you will not need to deal with the code, because all the process is pretty easy.

Collapse
 
olvajownday profile image
OlvaJownday

I'm sure no one would want any data to be exposed without their knowledge. As a way to protect your e-mails, but also as a convenient cloud storage solution, Beeble beeble.com/en/faq-en is worth a try. All the data you upload to the platform is protected by end-to-end encryption and is not accessible even by the platform's experts.

Collapse
 
ivoryhoward profile image
IvoryHoward • Edited

LinkedIn is a great place to find customers, but it's important to remember that salespeople should be nice when approaching them. They should be courteous, offer value, and be polite. Remember, this is the first impression, so treat your prospects as if they are already customers. With GetProspect b2b leads database, salespeople can make more money and be more productive than ever before - getprospect.com/b2b-contact-database . It's never too late to start using LinkedIn.

Collapse
 
s0bacc profile image
S0bacc

What does this give? More secure use of email? I am looking for the optimal solution so as not to worry about the safety of data, confidential information and everything that is in my business mail.

Collapse
 
s0bacc profile image
S0bacc

I'm only learning JS. SOme aspects mentioned here are new for me and complex but hopefully, I'll be able to use these features in the future

Collapse
 
ashishdonga4 profile image
Ashish donga

I found it very helpful ☺️ thank you