Monday, January 20, 2025
HomeProgrammingHow to send an email from JavaScript

How to send an email from JavaScript

Sending an email directly from JavaScript running in the browser is not possible for security and privacy reasons. However, there are workarounds to achieve this functionality using a server-side email service or a third-party API.

Here are two common approaches to sending emails from JavaScript:

1. **Using an Email API (e.g., EmailJS)

EmailJS is a service that allows you to send emails directly from JavaScript, using third-party SMTP servers, without needing your own server-side code.

Steps to send an email using EmailJS:

  1. Sign Up for EmailJS:
    • Go to EmailJS and create a free account.
    • Create an email service (e.g., Gmail, Outlook, or any other supported service).
    • Get your Service ID, Template ID, and User ID.
  2. Include the EmailJS SDK in your JavaScript code: You can either install the library using a package manager (like npm) or use the script tag to include it directly.

    For including via script tag:

    <script type="text/javascript" src="https://cdn.emailjs.com/dist/email.min.js"></script>
    
  3. Set up your EmailJS service and send the email:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Email with JavaScript</title>
</head>
<body>

    <h1>Send Email</h1>

    <form id="email-form">
        <input type="text" id="user_name" placeholder="Your Name" required><br>
        <input type="email" id="user_email" placeholder="Your Email" required><br>
        <textarea id="message" placeholder="Your Message" required></textarea><br>
        <button type="submit">Send Email</button>
    </form>

    <script type="text/javascript">
        // Initialize EmailJS with your user ID
        emailjs.init('YOUR_USER_ID'); // replace with your EmailJS user ID

        // Handle form submission
        document.getElementById('email-form').addEventListener('submit', function(event) {
            event.preventDefault();  // Prevent form from reloading the page

            // Get form values
            var user_name = document.getElementById('user_name').value;
            var user_email = document.getElementById('user_email').value;
            var message = document.getElementById('message').value;

            // Send email via EmailJS
            emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', {
                from_name: user_name,
                from_email: user_email,
                message: message
            })
            .then(function(response) {
                console.log('Email sent successfully!', response);
                alert('Email sent successfully!');
            }, function(error) {
                console.error('Error sending email', error);
                alert('Failed to send email');
            });
        });
    </script>

</body>
</html>

Explanation:

  • Replace YOUR_USER_ID, YOUR_SERVICE_ID, and YOUR_TEMPLATE_ID with the values you get from the EmailJS dashboard.
  • The form collects the user’s name, email, and message.
  • When the form is submitted, the emailjs.send() method is called to send the email using the provided template and data.
See also  How To Write Test Cases In Java

2. Using a Backend Server (Node.js) to Send Emails

If you don’t want to rely on a third-party service like EmailJS, you can create your own backend server using Node.js and an email sending service like Nodemailer.

See also  What is an API (Application Programming Interface)?

Steps:

  1. Set up a Node.js server and use Nodemailer to send emails.

Install Nodemailer:

npm install nodemailer
  1. Create a basic Node.js server to send an email:
// server.js
const express = require('express');
const nodemailer = require('nodemailer');
const app = express();

app.use(express.json());

// Create a POST route to send the email
app.post('/send-email', (req, res) => {
    const { to, subject, text } = req.body;

    // Create a transporter using your SMTP service (e.g., Gmail)
    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '[email protected]', // your email
            pass: 'your-email-password'    // your email password or app-specific password
        }
    });

    // Email options
    const mailOptions = {
        from: '[email protected]',
        to: to,
        subject: subject,
        text: text
    };

    // Send email
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return res.status(500).send('Error sending email: ' + error);
        }
        res.status(200).send('Email sent: ' + info.response);
    });
});

// Start the server
app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
  1. Call the API from the browser (JavaScript):
See also  How can you create a branch in Git from another branch?

You can now use fetch or axios from the frontend to send a request to the server to send an email:

fetch('http://localhost:3000/send-email', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        to: '[email protected]',
        subject: 'Test Email',
        text: 'This is a test email sent from JavaScript'
    })
})
.then(response => response.json())
.then(data => console.log('Email sent successfully', data))
.catch(error => console.error('Error:', error));

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x