+ 5

How to send email with javascript?

18th Nov 2018, 1:03 PM
Jingga Sona
Jingga Sona - avatar
7 ответов
+ 4
I don't think you can do that directly from Javascript , because the code is executed on client side not server side therefore its not a good even if its possible having your email credential visible to the user .
18th Nov 2018, 1:27 PM
S1M0
S1M0 - avatar
+ 4
Use AJAX. Here is a sample: // script.js var req = new XMLHttpRequest(); req.onreadystatechange = function() { if(this.readyState == 4) { if(this.status == 200) { alert("Sent!"); } else { alert("Error " + this.status + ": " + this.statusText); // For error messages } } }; req.open("GET", "server.php"); req.send(); Server.php: <?php // the message $msg = "First line of text\nSecond line of text"; // use wordwrap() if lines are longer than 70 characters $msg = wordwrap($msg, 70); // send email mail("someone@example.com", "My subject", $msg); ?> But you will have to set up a server, which will be a pain. So I would recommend using a JS library to do the work for you. 😊
18th Nov 2018, 8:49 PM
Rowsej
Rowsej - avatar
+ 4
It's possible for front end JavaScript to use third-party mail service to send mail. One of them is invotes. I have used it for some SoloLearn members to post me private messages last time, before SoloLearn added chat feature. Here is the contact me form using invotes service: https://code.sololearn.com/WuSY91lRBo0G/?ref=app Reference : invotes.com
19th Nov 2018, 12:18 PM
Calviղ
Calviղ - avatar
+ 4
Thanks Calviղ! Im a front ended, I tought its impossible, Thank You
19th Nov 2018, 12:29 PM
Jingga Sona
Jingga Sona - avatar
+ 3
Thanks everyone!
18th Nov 2018, 10:29 PM
Jingga Sona
Jingga Sona - avatar
+ 3
[meta, FYI -> future: raw sockets] The W3C Working Group has a proposal to implement TCP and UDP raw sockets. https://www.w3.org/TR/tcp-udp-sockets/ Unlike WebSockets--which require a special websocket listener--this means that at some point it may be possible to "HELO" (or "EHLO") a SMTP server directly without relying on web protocols. The security implications are not trivial (so it may struggle), but it's not the only thing disrupting JavaScript's status quo (e.g., WebAssembly, asm.js) so just remember this as a possible major change during your career.
19th Nov 2018, 5:01 PM
Kirk Schafer
Kirk Schafer - avatar