I'm writing a HTML page with a registration button that should just silently send an email without opening the local mail client. Here is my HTML:
<form method="post" action="">
<input type="text" id="email_address" name="name" placeholder="Enter your email address..." required>
<button onclick="sendMail(); return false">Send Email</button>
</form>
... and here is my JavaScript code:
<script type="text/javascript">
function sendMail() {
var link = 'mailto:[email protected]?subject=Message from '
+document.getElementById('email_address').value
+'&body='+document.getElementById('email_address').value;
window.location.href = link;
}
</script>
The code above works... but it opens the local email client. If I remove the return
statement in the onclick
attribute like this:
<form method="post" action="">
<input type="text" id="email_address" name="name" placeholder="Enter your email address..." required>
<button onclick="sendMail()">Send Email</button>
</form>
... then the email is not sent at all. Am I missing something?
Any help would be reeeally appreciated :-)
Can I send emails with JS or not? You can't send emails using JavaScript code alone due to the lack of support for server sockets. For this, you need a server-side language that talks to the SMTP server. You can use JS in conjunction with a server script that will send emails from the browser based on your requests.
You can use 'mailto:[email protected]' in the action field of the form. When the user presses the submit button of the form, the browser will first show a warning box that the user's email address will be revealed to the recipient.
The simplest way to send a message is to use QuickSend method of Smtp class (this method is static, it does not require you to create an instance of Smtp class). QuickSend method allows you to send e-mails out even if you do not have an SMTP relay server.
You need a server-side support to achieve this. Basically your form should be posted (AJAX is fine as well) to the server and that server should connect via SMTP to some mail provider and send that e-mail.
Even if it was possible to send e-mails directly using JavaScript (that is from users computer), the user would still have to connect to some SMTP server (like gmail.com), provide SMTP credentials, etc. This is normally handled on the server-side (in your application), which knows these credentials.
You cannot cause the user's browser to send email silently. That would be a horrible security problem as any website could use their system as a spam relay and/or harvest their email address.
You need to make an HTTP request to a server side process (written in the language of your choice) which sends the mail from your server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With