Sending emails with Javascript


The way I'm doing it now is basically like this:


<textarea id="myText">
    Lorem ipsum...
<button onclick="sendMail(); return false">Send</button>

The Javascript:

function sendMail() {
    var link = "mailto:[email protected]"
             + "[email protected]"
             + "&subject=" + encodeURIComponent("This is my subject")
             + "&body=" + encodeURIComponent(document.getElementById('myText').value)
    window.location.href = link;

This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.

Here's the way doing it using jQuery and an "element" to click on :

    $(location).attr('href', 'mailto:?subject='
                             + encodeURIComponent("This is my subject")
                             + "&body=" 
                             + encodeURIComponent("This is my body")

Then, you can get your contents either by feeding it from input fields (ie. using $('#input1').val() or by a server side script with $.get('...'). Have fun

You don't need any javascript, you just need your href to be coded like this:

<a href="mailto:[email protected]">email me here!</a>