Comments:"Sending Emails & Building Contact Forms in Pure Javascript"
URL:https://squaresend.com/blog/sending-emails-with-javascript
Today, we are releasing mailto.js, a lightweight client-side library for sending emails with JavaScript.
The library itself is simple and consists of only one public function (for sending mail) but it can make your life easier if you want to build contact forms or custom feedback forms without the hassle (and verbosity) of a server.
Integration
Assuming you're familiar with the basics of JavaScript or jQuery, here's how you use it:
<script type="text/javascript" src="https://squaresend.com/mailto.js"></script><script type="text/javascript"> var data = {}; data.to = "you@example.com"; data.from = "Sender Name<sender@example.com>"; data.subject = "The subject"; data.message = "The message"; Squaresend.mailto(data, function(response){ if ( response.error ) { alert("Error: "+response.error); } else { alert("Message sent"); } });</script>
The function accepts two parameters: data and callback. Callback's response will give out either response.error
or response.success
.
Both responses are strings containing the error or success message.
Validation
The function only checks for validation errors in the sender so it's best to validate the rest of your form with JavaScript before giving it to mailto. If you're using jQuery, this is fairly easy to do. You can cook up your own or grab a library from the web.
<script type="text/javascript"> $("form").submit(function(){ var email = $("#email").val(); var message = $("#message").val(); if ( email && message && email.indexOf("@") > -1 ) { Squaresend.mailto(data, function(){}); } });</script>
Examples
This example demonstrates using mailto.js with a simple, custom feedback form.
<form method="post"><input type="text" id="email" placeholder="Email address" /><br /><textarea placeholder="Please describe your issue..." id="issue"><textarea></form>
You can retrieve the user's ip address and user agent using custom $sqs_variables
we've provided.
<script type="text/javascript"> data.to = "you@example.com"; data.from = $("#email").val(); data.message = "Ip address: $sqs_ip_address \n"+ "User agent: $sqs_user_agent \n"+ "Issue: " + $("#issue").val();</script>
The from attribute can be just an email address or a name and email address formatted like this: Name<email>
To prevent spammers from abusing the library, we require the recipient email addresses to be authorized. Authorization simply tells us to accept mails sent to that address. The process takes about 10 seconds to complete.
After authorizing your account you can recieve 100 emails a month free. You can always upgrade if you need more.
Authorize your email Log in if you already have an account.