+ 5
How to send email with javascript?
7 Antworten
+ 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 .
+ 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. 😊
+ 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
+ 4
Thanks Calviղ! Im a front ended, I tought its impossible, Thank You
+ 3
Thanks everyone!
+ 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.