I want users to be able to send an email directly from my site using JavaScript, without triggering a page refresh. Here’s the setup I have so far:
<form action="javascript:sendMail();" name="pmForm" id="pmForm" method="post">
Enter Friend's Email:
<input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:98%;" />
<input name="pmSubmit" type="submit" value="Invite" />
</form>
I’ve seen examples using the mailto: method, but my understanding is that it only opens the user’s default email client and doesn’t actually send the email directly.
What and how should I implement inside the javascript send email function so that it can actually send the email behind the scenes, ideally through an API or another backend-supported method?
Hi Neha,
The most reliable way to handle a JavaScript send email function is to use an email-sending API like EmailJS, SendGrid, or your own backend.
Here’s the general idea:
function sendMail() {
const templateParams = {
to_email: document.getElementById("pmSubject").value,
message: "You’ve been invited!",
};
emailjs.send('service_id', 'template_id', templateParams, 'your_public_key')
.then(response => {
alert("Email sent successfully!");
})
.catch(error => {
console.error("Email sending failed", error);
});
}
This method keeps your email logic secure and avoids exposing credentials. It’s a cleaner, modern way to handle javascript send email without reloading the page.
If you’re just looking for a quick and simple approach and you’re okay relying on the user’s default email app you can use the mailto: scheme
.
function sendMail() {
const email = document.getElementById("pmSubject").value;
window.location.href = `mailto:${email}?subject=Invite&body=You've been invited!`;
}
This isn’t a true javascript send email method because it doesn’t actually send the email directly, it just opens the user’s email client with pre-filled info. Still, it’s an easy win for small projects.
If you have access to a backend server (Node.js, PHP, etc.), you can use fetch() to POST data to your server and have it send the email.
function sendMail() {
const email = document.getElementById("pmSubject").value;
fetch("/send-email", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ to: email, subject: "Invite", message: "Join us!" })
})
.then(res => res.json())
.then(data => {
alert("Email sent from server!");
})
.catch(err => {
console.error("Email send failed", err);
});
}
This gives you complete control and is a more advanced but proper way to handle a JavaScript send email use case for real applications.