2026-07-15

How to send an email from JavaScript

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

How to send an email from JavaScript

How to Send an Email from JavaScript: The Server-Side Truth

As developers, we often look for ways to make web applications more interactive. One common request is the desire to trigger actions—like sending an email—directly from client-side JavaScript without forcing a full page reload. While this sounds like a straightforward front-end task, it touches upon a fundamental security and architectural boundary: client-side JavaScript cannot directly access or execute server-side functions like sending emails.

This post will demystify how to achieve the goal of sending an email via a website using JavaScript, focusing on the necessary architecture that separates the presentation layer from the business logic.


The Limitation of Client-Side Email Functions

You correctly noted that methods like the mailto: protocol only open the user's default email application. This is because sending an email requires authentication (SMTP credentials) and access to a Mail Transfer Agent (MTA), which must be handled securely on a server.

Attempting to put all the email logic directly into a JavaScript function, as in your example function sendMail() { /* ...code here... */ }, will fail for security reasons. If you were to embed sensitive SMTP credentials directly into client-side JavaScript, anyone viewing your source code could steal those credentials and abuse your email account.

Therefore, the solution is not to make JavaScript send the email, but to use JavaScript to request an action from a trusted backend server, which then handles the actual email delivery.

The Correct Architecture: Frontend-Backend Communication

The proper way to handle form submissions or sensitive operations like sending emails is through an asynchronous request, typically using fetch or XMLHttpRequest (AJAX).

Here is the conceptual flow we must follow:

  1. Frontend (JavaScript): Collect the user input (email, subject) and package it into a JSON object.
  2. Request: Send this data to a specific URL endpoint on your web server using an HTTP POST request.
  3. Backend (Server - e.g., Laravel): The server receives the request, validates the data, and executes the secure logic to connect to an external mail service (like SendGrid or an internal SMTP server) and dispatch the email.

This separation ensures that sensitive operations remain protected on the server, which is a core principle in building robust applications like those developed using frameworks such as Laravel.

Step-by-Step Implementation Example

Let's transform your initial idea into a functional pattern. We will use JavaScript to capture the form data and send it to a controller route on the server.

1. HTML Setup (The Form)

We keep the HTML simple, focusing only on collecting necessary data:

<form id="emailForm" action="/send-mail" method="POST">
    Enter Friend's Email:
    <input type="text" name="email" id="emailInput" required>
    <input type="text" name="subject" id="subjectInput" required>
    <button type="submit">Send Invitation</button>
</form>

2. JavaScript Implementation (The Fetch Request)

We attach an event listener to the form submission, prevent the default browser submission, and use fetch to send the data asynchronously:

document.getElementById('emailForm').addEventListener('submit', async function(event) {
    event.preventDefault(); // Stop the traditional form submission

    const email = document.getElementById('emailInput').value;
    const subject = document.getElementById('subjectInput').value;

    try {
        const response = await fetch('/send-mail', { // This targets your server route
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email: email, subject: subject }),
        });

        if (response.ok) {
            alert('Email sent successfully!');
            document.getElementById('emailForm').reset();
        } else {
            alert('Error sending email. Please try again.');
        }
    } catch (error) {
        console.error('Network or Fetch Error:', error);
        alert('An unexpected error occurred.');
    }
});

3. Backend Logic (The Server Side - Conceptual PHP/Laravel)

On the server side, your route (/send-mail) receives the JSON data and uses secure environment variables to send the actual email:

// Example of a Laravel Controller method handling the request
use Illuminate\Http\Request;

class MailController extends Controller
{
    public function sendMail(Request $request)
    {
        // 1. Validation (Crucial for security)
        $request->validate([
            'email' => 'required|email',
            'subject' => 'required|string',
        ]);

        $recipient = $request->input('email');
        $subject = $request->input('subject');

        // 2. Actual Email Sending Logic (Using Laravel's Mail facade)
        try {
            Mail::raw("Invitation: {$subject}", function ($message) use ($recipient) {
                $message->to($recipient)->send();
            });

            return response()->json(['status' => 'success', 'message' => 'Email dispatched.']);

        } catch (\Exception $e) {
            // Log the error if mail fails
            \Log::error("Email sending failed: " . $e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'Failed to send email.'], 500);
        }
    }
}

Conclusion

To summarize, JavaScript is the perfect tool for creating responsive, interactive user interfaces. However, when dealing with sensitive operations like sending emails, we must adhere to the principle of separation of concerns. Use JavaScript purely for gathering input and initiating asynchronous requests. Let your backend framework—whether it’s Laravel or any other robust system—be responsible for secure execution of business logic, authentication, and external service communication. This approach ensures your application is secure, scalable, and maintainable, following best practices in modern web development.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.