How do I send email with JavaScript without opening the mail client?

j3d picture j3d · Jan 10, 2013 · Viewed 110.5k times · Source

I'm writing a HTML page with a registration button that should just silently send an email without opening the local mail client. Here is my HTML:

<form method="post" action="">
    <input type="text" id="email_address" name="name" placeholder="Enter your email address..." required>
    <button onclick="sendMail(); return false">Send Email</button>
</form>

... and here is my JavaScript code:

<script type="text/javascript">
  function sendMail() {
    var link = 'mailto:[email protected]?subject=Message from '
             +document.getElementById('email_address').value
             +'&body='+document.getElementById('email_address').value;
    window.location.href = link;
}
</script>

The code above works... but it opens the local email client. If I remove the return statement in the onclick attribute like this:

<form method="post" action="">
    <input type="text" id="email_address" name="name" placeholder="Enter your email address..." required>
    <button onclick="sendMail()">Send Email</button>
</form>

... then the email is not sent at all. Am I missing something?

Any help would be reeeally appreciated :-)

Answer

Quentin picture Quentin · Jan 10, 2013

You cannot cause the user's browser to send email silently. That would be a horrible security problem as any website could use their system as a spam relay and/or harvest their email address.

You need to make an HTTP request to a server side process (written in the language of your choice) which sends the mail from your server.