Sending emails with Javascript
Asked Answered
S

9

120

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?

Sasser answered 7/11, 2008 at 3:33 Comment(1)
#8092Roo
S
155

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:[email protected]"
             + "[email protected]"
             + "&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.

Sasser answered 7/11, 2008 at 3:33 Comment(10)
This is a pretty roundabout way of doing this when you can just set href attribute to the same content instead of using javascript.Anisometropia
Not roundabout if you want to include the contents of the textarea in the email. Also a good method to hide your email from spam harvesters.Surtout
@Gordon- that is assumed the email harvester doesn't regex inline javascript or follow <script src="">Alible
Use encodeURIComponent in preference to escape which follows arbitrary rules different from URL-encoding. Although Unicode characters are still likely to fail... but then the whole thing is very likely to fail anyway. mailto links with parameters are super-unreliable and shouldn't really be used.Very
bobince: yeah I figured it's a dodgy way to do it, but what's the alternative?Sasser
How can i populate the mailto box with an input on the page.. i tried something like this.. var link = "mailto:" + escape(document.getElementById('myTex').value) but to no avail it didn't work. Any help?Stanzel
Help Please, I would love to get this last portion fixed. I love this function by the way too.Stanzel
I modified your code because I wanted a way to cut down on spammers getting the email address directly, so I used some text for the link and passed my ng-click to a function call in a controller using Angularjs 1x. Thanks for posting!Headwards
Is it possible to attach a zip file to this mail too? @SasserAppreciable
@Appreciable I haven't tried, but I'd say almost certainly not.Sasser
M
20

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

Metro answered 20/2, 2012 at 18:0 Comment(2)
This is still subject to URL size limitations, just as the OP has mentioned.Surat
I just want to know that, It's taking time when we hit the send button?Antemeridian
A
15

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>
Anisometropia answered 7/11, 2008 at 3:42 Comment(3)
I guess I was expecting that the real code filled in the addresses dynamically.Befog
@Befog If the email addresses are known on the page at the time the anchor element is clicked, you could try giving the anchor an ID and setting its href value when the addresses are chosen. If a post is needed to get the email addresses at the time the click happens, this probably would not work.Apologete
on mac: target="_blank" is also requiredEustatius
A
5

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);
Alible answered 7/11, 2008 at 3:47 Comment(0)
F
5

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"
);
Feriga answered 21/1, 2018 at 16:19 Comment(2)
With this you expose the data of your SMTP server, It's best to do it on the server side with Node or PHP, thanks equallyHeard
Have you tried the button "Setup an SMTP server here" ? You can find it in the link shared in the answer.Feriga
B
3

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.

Befog answered 7/11, 2008 at 3:41 Comment(3)
the idea was that my application fills the body for them. I'll edit the question to make that clearer...Sasser
But why write an email client when you are just going to open one to send the mail?Befog
it's not an email client, it's just a page on my website which prefills an email message.Sasser
D
2

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.

Daniel answered 22/9, 2015 at 17:13 Comment(1)
> "But if nowadays "email client" is always set, automatically, potentially to a webmail client, I'll be happy to know." ... This is supported by modern browsers, eg: support.google.com/a/users/answer/9308783?hl=enSasser
I
1

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();
Invaluable answered 9/10, 2015 at 14:45 Comment(1)
Why GET and not POST? if message is big enough it will be truncated at some point.Hohenlinden
T
1

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).

Transept answered 13/1, 2021 at 11:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.