Search code examples
javascriptmailto

"Mailto:" doesn't send email


I wrote this simple code:

var email;
do {
     email = prompt('Inserisci il tuo indirizzo eMail');
     if ((email.indexOf("@") == (-1)) || (email == "") || (email == undefined)) {
            alert("Inserisci un indirizzo mail valido");
        }
    }
while ((email.indexOf("@") == (-1)) || (email == "") || (email == undefined));

var subject = ('My Armchair');

var body = new Array();
body[0] = sessionStorage.getItem('imuno');
body[1] = sessionStorage.getItem('imdue');
location.href = "mailto:babini.francesco@queensrl.net" + email + '?subject=' + subject + '&body=' + body[0] + body[1];
location.href = "../index.html";

The check is ok, but it doesn't send the email, someone knows why? Thank you!


Solution

  • OK, first you cannot send emails in (browser) javascript. You are going to need server-side code to do so.

    At most, doing location.href = "mailto:[…]"; will open the visitor's default mail application with part of it pre filled, but the visitor will still need to click on the send button. And the sender of the email will be the visitor, not you/your website.

    If that's what your looking for (the website visitor is actually manually sending the email, not you), you could open a popup for the mailto: link instead of using window.href: window.open("mailto:[…]")

    Otherwise, you'll need a server-side language (PHP, Node.js, etc.) with the code to send the email and add ajax request telling your server to do so in your current JS script.

    You should look for PHPMailer (PHP) : https://github.com/PHPMailer/PHPMailer
    or
    Nodemailer (Node.js) : https://nodemailer.com/