How to send an email from JavaScript?


Sending emails from javascript is a common feature in most web applications. It allows you to automate notifications, send user−generated content, or facilitate communication with your users. We can use different methods like using Malito protocol, sending Emails with a Server−Side Language, and Implementing Email Sending through an API to send emails from Javascript. In this article, we will explore all of these methods to send email using javascript.

Basics of Sending Email

Before implementing the email−sending feature using different libraries and methods we need to what are the basic requirements to send emails. At a high level, sending an email requires two main elements: the sender's email address and the recipient's email address. Also, you need an SMTP (Simple Mail Transfer Protocol) server to handle the email delivery.

Method 1:Using the Mailto Protocol

The simplest way to send an email from JavaScript is by utilizing the "mailto" protocol. It simply generates an email message with a pre−filled subject, recipient, and body. When a user clicks on a "mailto" link, it automatically opens their default email client with the pre−populated information.

Example

In the example below, we define the recipient's email address, subject, and body of the email. We then construct a "mailto" link by concatenating the values together and ensuring proper encoding using encodeURIComponent(). Finally, we set the window.location.href property to the generated mailto link, triggering the user's default email client to open with the pre−filled information.

const recipient = 'example@example.com';
const subject = 'Hello';
const body = 'This is the body of the email.';

const mailtoLink = `mailto:${recipient}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;

window.location.href = mailtoLink;

Output

On opening the Malito link generated in the browser, it will open the user's default email client with a new email draft containing the pre−filled subject, recipient, and body. The user can make any necessary modifications before sending the email.

mailto:example@example.com?subject=Hello&body=This%20is%20the%20body%20of%20the%20email.

Method 2: Sending Emails with a Server−Side Language

The Malito protocol has some limitations to use. It relies on the user's email client to send the email and lacks control over the email delivery process. To overcome these limitations, you can use a server−side language like Node.js or PHP to handle the email−sending process.

Example

const nodemailer = require('nodemailer');

async function sendEmail() {
  try {
    const transporter = nodemailer.createTransport({
      service: 'Gmail',
      auth: {
        user: 'your-email@gmail.com',
        pass: 'your-password'
      }
    });

    const mailOptions = {
      from: 'your-email@gmail.com',
      to: 'recipient@example.com',
      subject: 'Hello',
      text: 'This is the body of the email.'
    };

    const info = await transporter.sendMail(mailOptions);
    console.log('Email sent:', info.messageId);
  } catch (error) {
    console.error('Error occurred:', error);
  }
}

sendEmail();

Output

Email sent: <6fd37d54-7882-c074-5886-85abc286ac8c@gmail.com>

Note:You have to generate your app specific password to send the mail if you have enabled 2FA authentication in you mail login.

Method 3: Implementing Email Sending through an API

Another approach to sending emails from JavaScript is by integrating with an email delivery service or an API. This method provides more flexibility, control, and scalability for sending emails.

Example

Using SendGrid API

In the below example, we use the SendGrid API to send emails. First, we set the API key using setApiKey() from the @sendgrid/mail package. Then, we define the email details such as the recipient, sender, subject, and text content. We pass this information to the send() method, which returns a promise. We handle the success and error cases accordingly.

Note:You can get the sendgrid api key by signing up on sendgrid platform and creating your own API key.

const apiKey = 'your-sendgrid-api-key';
const sgMail = require('@sendgrid/mail');

sgMail.setApiKey(apiKey);

const msg = {
  to: 'recipient@example.com',
  from: 'sender@example.com',
  subject: 'Hello',
  text: 'This is the body of the email.'
};

sgMail.send(msg)
  .then(() => {
    console.log('Email sent successfully');
  })
  .catch((error) => {
    console.error('Error occurred:', error);
  });

Output

Email sent successfully

Conclusion

In this article, we discussed how we can send email from javascript using different methods. We began with the "mailto" protocol, which is useful for basic email functionality. Next, we discussed sending emails using a server−side language like Node.js or PHP, providing more control over the email delivery process. Lastly, we explored sending emails through an API, which offers flexibility and scalability. Remember to handle errors appropriately when sending emails, as failures can occur due to incorrect credentials, network issues, or limitations imposed by email service providers.

Updated on: 18-Jul-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements