How do I send email with JavaScript without opening the mail client? – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and html. Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about How do I send email with JavaScript without opening the mail client?.
Problem :
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:hello@domain.com?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 🙂
Solution :
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.
Directly From Client
Send an email using only JavaScript
in short:
1. register for Mandrill to get an API key
2. load jQuery
3. use $.ajax to send an email
Like this –
function sendMail() {
$.ajax({
type: 'POST',
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
'key': 'YOUR API KEY HERE',
'message': {
'from_email': 'YOUR@EMAIL.HERE',
'to': [
{
'email': 'RECIPIENT@EMAIL.HERE',
'name': 'RECIPIENT NAME (OPTIONAL)',
'type': 'to'
}
],
'autotext': 'true',
'subject': 'YOUR SUBJECT HERE!',
'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
}
}
}).done(function(response) {
console.log(response); // if you're into that sorta thing
});
}
https://medium.com/design-startups/b53319616782
Note: Keep in mind that your API key is visible to anyone, so any malicious user may use your key to send out emails that can eat up your quota.
Indirect via Your Server – secure
To overcome the above vulnerability, you can modify your own server to send the email after session based authentication.
node.js – https://www.npmjs.org/package/node-mandrill
var mandrill = require('node-mandrill')('<your API Key>');
function sendEmail ( _name, _email, _subject, _message) {
mandrill('/messages/send', {
message: {
to: [{email: _email , name: _name}],
from_email: 'noreply@yourdomain.com',
subject: _subject,
text: _message
}
}, function(error, response){
if (error) console.log( error );
else console.log(response);
});
}
// define your own email api which points to your server.
app.post( '/api/sendemail/', function(req, res){
var _name = req.body.name;
var _email = req.body.email;
var _subject = req.body.subject;
var _messsage = req.body.message;
//implement your spam protection or checks.
sendEmail ( _name, _email, _subject, _message );
});
and then use use $.ajax on client to call your email API.
You can’t do it with client side script only… you could make an AJAX call to some server side code that will send an email…
I think you can use smtpjs.com
There needs to be some type of backend framework to send the email. This can be done via PHP/ASP.NET, or with the local mail client. If you want the user to see nothing, the best way is to tap into those by an AJAX call to a separate send_email file.
You need to do it directly on a server. But a better way is using PHP. I have heard that PHP has a special code that can send e-mail directly without opening the mail client.
Well, PHP can do this easily.
It can be done with the PHP mail()
function. Here’s what a simple function would look like:
<?php
$to_email = 'name@company.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply@company.com';
mail($to_email,$subject,$message,$headers);
?>
This will send a background e-mail to the recipient specified in the $to_email
.
The above example uses hard coded values in the source code for the email address and other details for simplicity.
Let’s assume you have to create a contact us form for users fill in the details and then submit.
- Users can accidently or intentional inject code in the headers which can result in sending spam mail
- To protect your system from such attacks, you can create a custom function that sanitizes and validates the values before the mail is sent.
Let’s create a custom function that validates and sanitizes the email address using the filter_var()
built in function.
Here’s an example code:
<?php
function sanitize_my_email($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
$to_email = 'name@company.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: noreply@company.com';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
echo "Invalid input";
} else { //send email
mail($to_email, $subject, $message, $headers);
echo "This email is sent using PHP Mail";
}
?>
We will now let this be a separate PHP file, for example sendmail.php
.
Then, will use this file on form submission, using the action
attribute of the form, like:
<form action="sendmail.php" method="post">
<input type="text" value="Your Name: ">
<input type="password" value="Set Up A Passworrd">
<input type="submit" value="Signup">
<input type="reset" value="Reset Form">
</form>
Hope I could help