Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 Mailto 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 understand 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.
<!DOCTYPE html>
<html>
<head>
<title>Send Email with Mailto</title>
</head>
<body>
<button onclick="sendEmail()">Send Email</button>
<script>
function sendEmail() {
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)}`;
console.log('Mailto link:', mailtoLink);
window.location.href = mailtoLink;
}
</script>
</body>
</html>
Output
On clicking the button, the mailto link is generated and the user's default email client opens 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 link: mailto:example@example.com?subject=Hello&body=This%20is%20the%20body%20of%20the%20email.
Method 2: Sending Emails with a Server-Side Language
The Mailto protocol has some limitations. 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 to handle the email-sending process.
Example
Here's how to send emails using Node.js with the Nodemailer package:
const nodemailer = require('nodemailer');
async function sendEmail() {
try {
const transporter = nodemailer.createTransporter({
service: 'Gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-app-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 need to generate an app-specific password to send emails if you have enabled 2FA authentication in your Gmail account.
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.
Note: You can get the SendGrid API key by signing up on the 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
Comparison of Methods
| Method | Ease of Use | Control | Server Required |
|---|---|---|---|
| Mailto Protocol | Very Easy | Limited | No |
| Server-Side (Node.js) | Moderate | High | Yes |
| Email API (SendGrid) | Moderate | High | Yes |
Conclusion
In this article, we discussed how to send emails from JavaScript using different methods. The mailto protocol is perfect for simple client-side email functionality, while server-side solutions with Node.js or email APIs like SendGrid provide greater control and reliability for production applications.
