Sending Emails with 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

How can I use JavaScript to send emails instantly?

Looking at the tutorial there is a key difference between your implementation and the one provided. Where you are using <button> the example uses <input type="button"> like below:

<input type="button" value="Send Email" onclick="send()"/>

Key difference is the button you are using is submitting the form element and refreshing the page so the send() function is never run.

With the above in place of the button the form is never submitted and the function is called.

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