Search code examples
javascripthtmlemailmailto

Can't get mailto tag to work in my website in javascript


In my website, I have a textarea and a button, and I want to receive an email whose body is the text written in the textarea box. A button will call a function on click which will send the email. After researching about this I found that people on various forums are suggesting to use the mailto: tag. However, when I use the mailto tag as in the code below, I don't receive any emails. My relevant code is as below;

HTML:

<textarea id="text"></textarea>
<button onclick="myFunction()">Click ME!</button>

Javascript:

function myFunction () {
    var x = document.getElementById("text").value;
    document.getElementById("p").innerHTML = x;
    'mailto:' + 'someone@gmail.com' + '?subject=' + Requests + '&body=' + x;
}

Solution

  • You did not reset the href atribute of the document. You simply calculated what that value would be. You need to set the location.href to 'mailto:' + 'someone@gmail.com' + '?subject=' + Requests + '&body=' + x;

    function myFunction () {
    var x = document.getElementById("text").value;
    var url = 'mailto:' + 'someone@gmail.com' + '?subject=' + "Requests" + '&body=' + x;
    window.open(url);
    document.getElementById("p").href = url;
    }
    <textarea id="text"></textarea>
    <button onclick="myFunction()">Click ME!</button>
    <a id="p">newlink</a>