How to populate MailTo link with a form action using Javascript

Someday you might want to have a form where the submit button goes to a MailTo: link. You might want to populate the email’s To: Subject: and Body.

Here is a plunk to do it:

Here is the html and javascript:

function sendemail()
    var body = "First name: " + document.getElementById("fn").value + "\n";
    body +=  "Last name: " + document.getElementById("ln").value;
    var email = document.getElementById("email").value;
    var location = "mailto:" + email + "?subject=Hello world&body=" + encodeURIComponent(body);
    window.location.href = location;
<form action="javascript: sendemail()">
First name:<br>
<input id="fn" type="text" name="firstname">
Last name:<br>
<input id="ln" type="text" name="lastname">
<input id="email" type="text" name="email">
<input type="submit" value="Submit">

Leave a Reply

How to post code in comments?