[javascript] Sending emails with Javascript

This is a little confusing to explain, so bear with me here...

I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with an email ready to go. The application would fill out the body of the email with predefined variables, to save the user having to type it themselves. They can then edit the message as desired, should it not exactly suit their purposes.

There's a number of reasons I want it to go via the user's local mail client, so getting the server to send the email is not an option: it has to be 100% client-side.

I already have a mostly-working solution running, and I'll post the details of that as an answer, I'm wondering if there's any better way?

This question is related to javascript email client-side

The answer is


If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.


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>

What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span>'

To which I'd have

.launchEmailClientLink {
cursor: pointer;
color: #00F;
}

and jQuery this into your onDomReady

$('.launchEmailClientLink').bind('click',sendMail);

If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.


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

$('#element').click(function(){
    $(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


The problem with the very idea is that the user has to have an email client, which is not the case if he rely on webmails, which is the case for many users. (at least there was no turn-around to redirect to this webmail when I investigated the issue a dozen years ago).

That's why the normal solution is to rely on php mail() for sending emails (server-side, then).

But if nowadays "email client" is always set, automatically, potentially to a webmail client, I'll be happy to know.


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

$('#element').click(function(){
    $(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 can use this free service: https://www.smtpjs.com

  1. Include the script:

<script src="https://smtpjs.com/v2/smtp.js"></script>

  1. Send an email using:
Email.send(
  "[email protected]",
  "[email protected]",
  "This is a subject",
  "this is the body",
  "smtp.yourisp.com",
  "username",
  "password"
);

What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span>'

To which I'd have

.launchEmailClientLink {
cursor: pointer;
color: #00F;
}

and jQuery this into your onDomReady

$('.launchEmailClientLink').bind('click',sendMail);

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>

Send request to mandrillapp.com:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        console.log(xhttp.responseText);
    }
}
xhttp.open('GET', 'https://mandrillapp.com/api/1.0/messages/send.json?message[from_email][email protected]&message[to][0][email][email protected]&message[subject]=??????%20?%207995.by&message[html]=xxxxxx&key=oxddROOvCpKCp6InvVDqiGw', true);
xhttp.send();

If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.


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>

What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span>'

To which I'd have

.launchEmailClientLink {
cursor: pointer;
color: #00F;
}

and jQuery this into your onDomReady

$('.launchEmailClientLink').bind('click',sendMail);

You can add the following to the <head> of your HTML file:

<script src="https://smtpjs.com/v3/smtp.js"></script>

<script type="text/javascript">
    function sendEmail() {
        Email.send({
            SecureToken: "security token of your smtp",
            To: "[email protected]",
            From: "[email protected]",
            Subject: "Subject...",
            Body: document.getElementById('text').value
        }).then( 
            message => alert("mail sent successfully")
        );
    }
</script>

and below is the HMTL part:

<textarea id="text">write text here...</textarea>
<input type="button" value="Send Email" onclick="sendEmail()">

So the sendEmail() function gets the inputs using:

document.getElementById('id_of_the_element').value

For example, you can add another HTML element such as the subject (with id="subject"):

<textarea id="subject">write text here...</textarea>

and get its value in the sendEmail() function:

Subject: document.getElementById('subject').value

And you are done!

Note: If you do not have a SMTP server you can create one for free here. And then encrypt your SMTP credentials here (the SecureToken attribute in sendEmail() corresponds to the encrypted credentials generated there).


Send request to mandrillapp.com:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        console.log(xhttp.responseText);
    }
}
xhttp.open('GET', 'https://mandrillapp.com/api/1.0/messages/send.json?message[from_email][email protected]&message[to][0][email][email protected]&message[subject]=??????%20?%207995.by&message[html]=xxxxxx&key=oxddROOvCpKCp6InvVDqiGw', true);
xhttp.send();

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>

What about having a live validation on the textbox, and once it goes over 2000 (or whatever the maximum threshold is) then display 'This email is too long to be completed in the browser, please <span class="launchEmailClientLink">launch what you have in your email client</span>'

To which I'd have

.launchEmailClientLink {
cursor: pointer;
color: #00F;
}

and jQuery this into your onDomReady

$('.launchEmailClientLink').bind('click',sendMail);

If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.


The problem with the very idea is that the user has to have an email client, which is not the case if he rely on webmails, which is the case for many users. (at least there was no turn-around to redirect to this webmail when I investigated the issue a dozen years ago).

That's why the normal solution is to rely on php mail() for sending emails (server-side, then).

But if nowadays "email client" is always set, automatically, potentially to a webmail client, I'll be happy to know.


You can add the following to the <head> of your HTML file:

<script src="https://smtpjs.com/v3/smtp.js"></script>

<script type="text/javascript">
    function sendEmail() {
        Email.send({
            SecureToken: "security token of your smtp",
            To: "[email protected]",
            From: "[email protected]",
            Subject: "Subject...",
            Body: document.getElementById('text').value
        }).then( 
            message => alert("mail sent successfully")
        );
    }
</script>

and below is the HMTL part:

<textarea id="text">write text here...</textarea>
<input type="button" value="Send Email" onclick="sendEmail()">

So the sendEmail() function gets the inputs using:

document.getElementById('id_of_the_element').value

For example, you can add another HTML element such as the subject (with id="subject"):

<textarea id="subject">write text here...</textarea>

and get its value in the sendEmail() function:

Subject: document.getElementById('subject').value

And you are done!

Note: If you do not have a SMTP server you can create one for free here. And then encrypt your SMTP credentials here (the SecureToken attribute in sendEmail() corresponds to the encrypted credentials generated there).


You can use this free service: https://www.smtpjs.com

  1. Include the script:

<script src="https://smtpjs.com/v2/smtp.js"></script>

  1. Send an email using:
Email.send(
  "[email protected]",
  "[email protected]",
  "This is a subject",
  "this is the body",
  "smtp.yourisp.com",
  "username",
  "password"
);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to email

Monitoring the Full Disclosure mailinglist require(vendor/autoload.php): failed to open stream Failed to authenticate on SMTP server error using gmail Expected response code 220 but got code "", with message "" in Laravel How to to send mail using gmail in Laravel? Laravel Mail::send() sending to multiple to or bcc addresses Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate How to validate an e-mail address in swift? PHP mail function doesn't complete sending of e-mail How to validate email id in angularJs using ng-pattern

Examples related to client-side

Getting query parameters from react-router hash fragment Single Page Application: advantages and disadvantages How to export JavaScript array info to csv (on client side)? Best practice for localization and globalization of strings and labels How can you use php in a javascript function How to create a file in memory for user to download, but not through server? Pass request headers in a jQuery AJAX GET call Image resizing client-side with JavaScript before upload to the server Print directly from browser without print popup window Sending emails with Javascript