How to send an email from JavaScript
Indirect via Your Server - Calling 3rd Party API - secure and recommended
Your server can call the 3rd Party API. The API Keys are not exposed to client.
node.js
const axios = require('axios');
async function sendEmail(name, email, subject, message) {
const data = JSON.stringify({
"Messages": [{
"From": {"Email": "<YOUR EMAIL>", "Name": "<YOUR NAME>"},
"To": [{"Email": email, "Name": name}],
"Subject": subject,
"TextPart": message
}]
});
const config = {
method: 'post',
url: 'https://api.mailjet.com/v3.1/send',
data: data,
headers: {'Content-Type': 'application/json'},
auth: {username: '<API Key>', password: '<Secret Key>'},
};
return axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
// define your own email api which points to your server.
app.post('/api/sendemail/', function (req, res) {
const {name, email, subject, message} = req.body;
//implement your spam protection or checks.
sendEmail(name, email, subject, message);
});
and then use use fetch on client side to call your email API.Use
from email
which you used to register on Mailjet. You can authenticate more addresses too. Mailjet offers a generous free tier.Update 2023: As pointed out in the comments the method below does not work any more due to CORS
This can be only useful if you want to test sending email and to do this
- visit https://api.mailjet.com/stats (yes a 404 page)
- and run this code in the browser console (with the secrets populated)
in short:
- register for Mailjet to get an API key and Secret
- use fetch to call API to send an email
function sendMail(name, email, subject, message) {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.set('Authorization', 'Basic ' + btoa('<API Key>'+":" +'<Secret Key>'));
const data = JSON.stringify({
"Messages": [{
"From": {"Email": "<YOUR EMAIL>", "Name": "<YOUR NAME>"},
"To": [{"Email": email, "Name": name}],
"Subject": subject,
"TextPart": message
}]
});
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: data,
};
fetch("https://api.mailjet.com/v3.1/send", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
sendMail('Test Name',"<YOUR EMAIL>",'Test Subject','Test Message')
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. Can I send mail using Javascript and jquery without a server?
You can not send an email direct from front-end using JavaScript, Jquery or any front-end framework/library externally using server or back-end. because your credentials are open to all and there are so many factors work behind that...
An option is to let each user use his or her sociable mail server, by doing a mailto: connection, which allows you to define the header data & including a quasi-header called 'body', which sets the content you require to pass in the message body.
You can Send Using:-
There are also some parameters to add:
However, you can append parameters to email like the following:-
Here are some parameters you can pass in the mail you want to send from front-end
mailto
:-add recipients,
note
:- if you want to add multiple recipients then add comma-separated as mentioned in the example.
&cc
= to add CC recipients,
&bcc
= to add BCC recipients,
&subject
= to add mail subject,
&body
= to add mail body,
Example:-
<a href="mailto:sendMe1@example.com?cc=sendMecc@example.com?bcc=sendMebcc@example.com?subject=Mail-SubJect
&body=Mail-Body....">
Send Me Email from Front-end
</a>
Some customer-service providers provide you to send an email with the help of their service smtpjs, formspree, emailjs, Google APIs, but this is not practical plus trusted.
How to send an email using jQuery and POST
You have multiple errors, first of all you are using element ids to pick up the data:
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
but the input elements themselves have no id attribute defined.Secondly, you are passing name, email and message, but in your PHP you are using name, email and text:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
However, even if correct all this is unnecessarily complicated, you can instead just serialize the form:In the HTML, add an id to the form:
<form enctype="multipart/form-data" id="frmemail">
In JS, pick up the form and serialize it:$(document).ready(function(){
$("#frmemail").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "email-php.php",
data: $("#frmemail").serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
});
});
And in PHP simply use the element names, you don't need ids for them:$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
Sending emails with Javascript
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:me@example.com"
+ "?cc=myCCaddress@example.com"
+ "&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.
Related Topics
Domnodeinserted Equivalent in Ie
Using Filesystem in Node.Js with Async/Await
Get Selected Value/Text from Select on Change
Catching Errors in JavaScript Promises with a First Level Try ... Catch
Regular Expression to Match Exactly 5 Digits
Load "Vanilla" JavaScript Libraries into Node.Js
Sort an Array by the "Levenshtein Distance" with Best Performance in JavaScript
Adding Script Tags in Angular Component Template
How to Create an Auto-Complete Combobox
Read a Text File Using Node.Js
Accessing JSON Object Keys Having Spaces
Window.Location.Reload with Clear Cache
Using Raw Image Data from Ajax Request for Data Uri
Access Properties of the Parent with a Handlebars 'Each' Loop
JavaScript Settimeout and Loops