21

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:hello@domain.com?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 :-)

j3d
  • 9,492
  • 22
  • 88
  • 172

8 Answers8

15

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
15

You need a server-side support to achieve this. Basically your form should be posted (AJAX is fine as well) to the server and that server should connect via SMTP to some mail provider and send that e-mail.

Even if it was possible to send e-mails directly using JavaScript (that is from users computer), the user would still have to connect to some SMTP server (like gmail.com), provide SMTP credentials, etc. This is normally handled on the server-side (in your application), which knows these credentials.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • That would be perfect since the server-side also hosts the mail server. Having said that, the idea would be to post the request using JavaScript and then have a script on the server side that actually sends the email with the local mail server. I'll look for an example on the Web... – j3d Jan 11 '13 at 19:44
9

Directly From Client


Send an email using only JavaScript

in short: 
1. register for Mandrill to get an API key
2. load jQuery
3. use $.ajax to send an email

Like this -

function sendMail() {
    $.ajax({
      type: 'POST',
      url: 'https://mandrillapp.com/api/1.0/messages/send.json',
      data: {
        'key': 'YOUR API KEY HERE',
        'message': {
          'from_email': 'YOUR@EMAIL.HERE',
          'to': [
              {
                'email': 'RECIPIENT@EMAIL.HERE',
                'name': 'RECIPIENT NAME (OPTIONAL)',
                'type': 'to'
              }
            ],
          'autotext': 'true',
          'subject': 'YOUR SUBJECT HERE!',
          'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
        }
      }
     }).done(function(response) {
       console.log(response); // if you're into that sorta thing
     });
}

https://medium.com/design-startups/b53319616782

Note: Keep in mind that your API key is visible to anyone, so any malicious user may use your key to send out emails that can eat up your quota.


Indirect via Your Server - secure


To overcome the above vulnerability, you can modify your own server to send the email after session based authentication.

node.js - https://www.npmjs.org/package/node-mandrill

var mandrill = require('node-mandrill')('<your API Key>'); 

function sendEmail ( _name, _email, _subject, _message) {
    mandrill('/messages/send', {
        message: {
            to: [{email: _email , name: _name}],
            from_email: 'noreply@yourdomain.com',
            subject: _subject,
            text: _message
        }
    }, function(error, response){
        if (error) console.log( error );
        else console.log(response);
    });
}

// define your own email api which points to your server.

app.post( '/api/sendemail/', function(req, res){

    var _name = req.body.name;
    var _email = req.body.email;
    var _subject = req.body.subject;
    var _messsage = req.body.message;

    //implement your spam protection or checks. 

    sendEmail ( _name, _email, _subject, _message );

});

and then use use $.ajax on client to call your email API.

rahulroy9202
  • 2,730
  • 3
  • 32
  • 45
4

You can't do it with client side script only... you could make an AJAX call to some server side code that will send an email...

Ads
  • 2,084
  • 2
  • 24
  • 34
2

I think you can use smtpjs.com

Louis
  • 2,548
  • 10
  • 63
  • 120
1

There needs to be some type of backend framework to send the email. This can be done via PHP/ASP.NET, or with the local mail client. If you want the user to see nothing, the best way is to tap into those by an AJAX call to a separate send_email file.

PlantTheIdea
  • 16,061
  • 5
  • 35
  • 40
1

Well, PHP can do this easily.

It can be done with the PHP mail() function. Here's what a simple function would look like:

<?php     
$to_email = 'name@company.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply@company.com';
mail($to_email,$subject,$message,$headers);
?>

This will send a background e-mail to the recipient specified in the $to_email.

The above example uses hard coded values in the source code for the email address and other details for simplicity.

Let’s assume you have to create a contact us form for users fill in the details and then submit.

  1. Users can accidently or intentional inject code in the headers which can result in sending spam mail
  2. To protect your system from such attacks, you can create a custom function that sanitizes and validates the values before the mail is sent.

Let’s create a custom function that validates and sanitizes the email address using the filter_var() built in function.

Here's an example code:

<?php 
function sanitize_my_email($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}
$to_email = 'name@company.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: noreply@company.com';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
    echo "Invalid input";
} else { //send email 
    mail($to_email, $subject, $message, $headers);
    echo "This email is sent using PHP Mail";
}
?>

We will now let this be a separate PHP file, for example sendmail.php.

Then, will use this file on form submission, using the action attribute of the form, like:

<form action="sendmail.php" method="post">
   <input type="text" value="Your Name: ">
   <input type="password" value="Set Up A Passworrd">
   <input type="submit" value="Signup">
   <input type="reset" value="Reset Form">
</form>

Hope I could help

SK-the-Learner
  • 523
  • 5
  • 18
0

You need to do it directly on a server. But a better way is using PHP. I have heard that PHP has a special code that can send e-mail directly without opening the mail client.

Tiago Salzmann
  • 184
  • 2
  • 14
  • 2
    Since php runs on the server, using php isn't quite _better_ than doing it on the server! – jahroy Jan 10 '13 at 23:03
  • 1
    PHP has no way to send email directly from the user's system. The email would be sent from the server. There is nothing *special* about this, any programming language could be used. PHP's primary advantage is that it is available on most cheap hosting. – Quentin Jan 10 '13 at 23:03