How to Send an Email from JavaScript

How to send an email from JavaScript

You can't send an email directly with javascript.

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

window.open('mailto:test@example.com');

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

window.open('mailto:test@example.com?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.

Sending email in Javascript

The query string should be start with ? not &

change &subject to ?subject

it should be //abc@example.com?subject=blahblahblah&body=testtest

Sending emails with Javascript

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

The HTML:

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

The Javascript:

function sendMail() {
var link = "mailto:me@example.com"
+ "?cc=myCCaddress@example.com"
+ "&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.



Related Topics



Leave a reply



Submit