How to send an email from JavaScript

user906357 picture user906357 · Sep 11, 2011 · Viewed 796.2k times · Source

I want my website to have the ability to send an email without refreshing the page. So I want to use Javascript.

<form action="javascript:sendMail();" name="pmForm" id="pmForm" method="post">
Enter Friend's Email:
<input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:98%;" />
<input name="pmSubmit" type="submit" value="Invite" />

Here is how I want to call the function, but I'm not sure what to put into the javascript function. From the research I've done I found an example that uses the mailto method, but my understanding is that doesn't actually send directly from the site.

So my question is where can I find what to put inside the JavaScript function to send an email directly from the website.

function sendMail() {
    /* ...code here...    */
}

Answer

Arnaud Le Blanc picture Arnaud Le Blanc · Sep 11, 2011

You can't send an email directly with javascript.

You can, however, open the user's mail client:

window.open('mailto:[email protected]');

There are also some parameters to pre-fill the subject and the body:

window.open('mailto:[email protected]?subject=subject&body=body');

Another solution would be to do an ajax call to your server, so that the server sends the email. Be careful not to allow anyone to send any email through your server.