set client cookie to prevent re-registration - javascript

I don't have access to run server-side code, so I can't do a PHP session for a registration form. I am going with a client cookie to ensure only one registration per person (per unique e-mail).
Following How do I set/unset cookie with jQuery? I thought I got the hang of it.
But it seems, even if I put in a new e-mail, it will always return alert("You've already registered");. Why is that?
$("#submitBtn").click(function (event) {
var subject = "Registration for Walk-a-thon",
name = document.getElementById("name").value,
email = document.getElementById("email").value,
message = document.getElementById("message").value;
if (!$.cookie('client_email_cookie')) {
$.cookie("client_email_cookie", email, { path: '/', expires : 10});
log("Cookie: " + $.cookie("client_email_cookie"));
var link = "mailto:Jun.Ma2#otis.com; Allison.Rocca#utc.com"
+ "?cc=daniel.turcotte#carrier.utc.com"
+ "&subject=" + escape(subject)
+ "&body=" + escape(message)
;
window.location.href = link;
}
else {
alert("You've already registered");
}
});

if (!$.cookie('client_email_cookie')) only checks to see if the cookie exists, it doesn't check its value.
$.cookie('client_email_cookie') returns the value of the cookie (in your case email). Compare that value to the email that was entered to see if it has been registered.
Also, not to state the obvious, but this can be easily defeated anyway by the user simply deleting the cookie if they so desire, registering from a different browser or computer, using private browsing, etc...

Related

How can I set a group of previously saved cookies in a Chrome Extension by using chrome.cookies.set()?

I'm trying to create a very simple Chrome extension to emulate Firefox containers and have a different session on each group of tabs. Right now, I'm focusing on cookies but I can't figure out how the chrome.cookies.set() works. I want my extension to detect when the user switches to a tab marked as another session's tab, save all previous session's cookies into a dictionary, delete all the browser cookies and then set all the browser cookies to all current session's cookies saved into the dictionary. The saving + removing all cookies works but I just can't do the setting part. Maybe you just can't set cookies manually this way this and you have to use something else. Also, I think my manifest.json file is fine, since I have the cookies, active tab, and <all_urls> permissions
function handleActivated(activeInfo) {
console.log("Tab " + activeInfo.tabId +
" was activated. From: " + getSession(activeInfo.tabId));
if (getSession(activeInfo.tabId) !== currentActiveSession) {
lastActiveSession = currentActiveSession;
currentActiveSession = getSession(activeInfo.tabId);
console.log("last session: " + lastActiveSession + " | current session: " + currentActiveSession);
//SWAPS COOKIES
chrome.cookies.getAll({}, (cookies) => {
sessionDictionary[lastActiveSession]["cookieStore"] = cookies;
for (let removedCookie of cookies) {
let urlString = "https://" + removedCookie.domain;
chrome.cookies.remove({ url: urlString, name: removedCookie.name });
}
for(let cookie of sessionDictionary[currentActiveSession]["cookieStore"]) {
let c = {
domain : cookie.domain,
expirationDate: cookie.expirationDate,
httpOnly: cookie.httpOnly,
name: cookie.name,
path: cookie.path,
sameSite: cookie.sameSite,
secure: cookie.secure,
storeId: cookie.storeId,
url: "https://" + cookie.domain,
value: cookie.value
}
chrome.cookies.set(c);
}
});
}
}
I'm not sure about the url property in the cookie I want to set. Also, I cannot set the hostOnly property so I just manually removed it.

PHP not accessing Javascript cookie

I am creating a small CRUD web app where I need the user to enter their password when they wish to delete an item from the database, I have an onClick() on the delete button on the HTML table which passes the ID of the product to be deleted to the js function.
When the function runs I wish to confirm that they really want to delete the product and then ask for their password and store it in a cookie. BUT IT DOES NOT SEEM TO WORK :(
I am setting a cookie using javascript like
document.cookie = 'password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php;
With this line of code, when I console.log(document.cookie), it shows me the cookie in the console like
password=admin,expires=Sat, 12 Dec 2020 08:40:38 GMT,path=/../includes/delete-product.inc.php; PHPSESSID=3n1l3q6ksqitdpc76hjrero9ja
when I redirect to another PHP page using window.open() I can not access this cookie.
print_r($_COOKIE); <- only shows me the PHPSESSID only.
When I explicitly try to access the cookie using the following line
$userPassword = $_COOKIE[password]; it gives me undefined index 'password'
This is my code.
myproject/admin/view-products.php (This is the page where I try to set the cookie using javascript)
function deletePrompt(id) {
const now = new Date();
const time = now.getTime();
const expiresIn = time + (50 * 1000);
now.setTime(expiresIn);
const path = `../includes/delete-product.inc.php`;
const intent = confirm("Are you sure you want to delete this products");
if (intent === true) {
const userPassword = prompt("Enter password");
document.cookie = `password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php`;
console.log(document.cookie);
return;
window.open(`../includes/delete-product.inc.php?id=${id}`, "_self");
}
}
myproject/includes/delete-product.inc.php (This is the PHP page where I need to access the cookie)
<?php
require_once "./database-connection.inc.php";
require_once "./functions.inc.php";
if (isset($_SESSION["adminId"])) {
$productId = $_GET["id"];
$userPassword = $_COOKIE["password"]; //<- This throws undefined index error
if (deleteProduct($connection, $productId, $userPassword)) {
header("location: ../admin/view-products.php?msg=deleted");
exit();
}
else {
header("location: ../admin/view-products.php?msg=incorrectPass");
exit();
}
}
else {
header("location: ../admin/login.php");
exit();
}
To anyone else facing this the problem, the solution is that cookies don't get sent across directories, so you need to have the recipient file in the same domain if you wish to transfer cookies across them otherwise it won't work.
eg.
Following pattern will work
youProject/someDirectory/file1
youProject/someDirectory/file2
Following will NOT WORK
youProject/someDirectory/file1
youProject/someOtherDirectory/file2

is it possible to redirect the user to same page after login using client side technology

I have searched quite a lot regarding my problem and I couldn't find any relevant tutorial. Moreover, I am not even sure if it is possible using client side technology.
Problem statement: For e.g I have many pages in my web app and if a user switch from index page to page 1 and then page 2. Now the user decides to login to my web site. I want to redirect the user to page 2 once the login is successful.
Current outcome: Once the login is successful user always seems to get redirected to the index page.
Desired outcome: Once the login is successful the user should stay on page 2.
Is it possible using client side technology? In PHP we could use sessions and all. But I am confined on using client side technology to achieve that.
Here is my login function
function login(params) {
if(checkEmpty("loginEmail") && checkEmpty("password")) {
var emailField = $("#loginEmail").val(),
passwordField = $("#password").val(),
data = "login=" + emailField + "&password=" + passwordField;
for (var key in params) {
data += "&" + key + "=" + params[key];
}
// Hide errors as default
$("#loginErrorWrapper").hide();
// Try to launch the "normal" submit operation to make browser save email-field's value to cache
$('#loginSubmitHidden').click();
// Send data to server and refresh the page if everything is ok
$.when(loginPost(data)).done(function(map) {
if(!hasErrors(map)) {
var lang = map.language;
if (lang != "") {
changeLanguage(lang)
}
else {
lang = 'en';
}
redirect("/" + lang + "/");
} else {
if (map.errorCode == "155") {
$.fancybox({
href : '#termsAcceptancePopup',
title : '',
beforeLoad : function() {
$('#acceptTermsButton').attr('onclick','javascript:login({policyChecked:true});$.fancybox.close();');
},
helpers : {
overlay : { closeClick: false }
}
});
} else {
var errorString = getErrorMessage(map);
$("#loginErrorWrapper").show();
$("#loginErrorWrapper").html(errorString);
}
}
});
}
}
Ajax request
function loginPost(data) {
return $.ajax({
url: "/some-api/login",
type: "POST",
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: true,
data:data
});
}
P.S -> I am not using PHP at all. I am working on a Java based web app.
So I have tried all the methods suggested in the comment section and all of them worked.
1) Using location.reload()
Once the user is logged in it just refresh the page.
2) Saving the last URL in a cookie
Calling the below function before calling redirect.
createCookie(value1, value2, value3);
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
3) Removing redirect("/" + lang + "/"); from my function since I am using ajax for login. However this method is not useful because once the user is logged in he/she will never know whether everything went fine or not unless he/she refresh the page manually or go to another page.
I am not certain which method is better (performance and loading time) - method 1 or method 2.

Share cookies with other domains

I know that it's possible to allow other domains to read our domain cookie as long as they're sub domains of the same parent domain.
For example, intranet.abc.com and extranet.abc.com can allow cookies to be read by each other by specifying the domain property to .abc.com
Now, I'm really in need that I can allow other domains to read my domain cookie (they are not sub domains of the same domain). I have searched a lot of discussions on the internet => all say "NO" due to security issues. I'm not sure if I missed a solution out there because I don't see any security issues in this case. My server clearly ALLOWS this cookie to be read by an XYZ.COM domain because the cookie does not contain any sensitive information and XYZ.COM domain is my trusted domain,
In my opinion, there should be a way to specify a list of other domains that are allowed to read a particular cookie in our domain, just like CORS, the server can decide if the information should be available to some trusted domains.
Please tell me if it's possible without using a workaround and if so, how to do it?
If it's not possible, I really would like to know why.
Some information about what I'm implementing:
I'm implementing a file download and on client side I need to detect whether the download is complete by periodically checking for a download token in the cookie using an interval in javascript.
The logic of the current system I'm working on at the moment may store the files in 2 different servers. If the file is missing in the current server, it will download file in another server (another domain)
Thank you very much.
You can read off-domain cookies by opening an iframe to specially instrumented page on the other domain and using the window.postMessage API to communicate between windows. HTML5 only, obviously.
Simplifying the postMessage API somewhat for brevity, consult MDN developer pages for full details.
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
<iframe id="ifrm" src="http://other.domain.com/getCookie.html"></iframe>
<script>
var iframe = document.getElementById('ifrm');
window.addEventListener('message', function (e) {
if (e.source === iframe.contentWindow && e.origin === 'other.domain.com') {
var cookie = e.data;
//do something with cookie
}
});
//wait for the iframe to load...maybe ping it first...then
iframe.contentWindow.postMessage('give me the cookie:cookie name', 'other.domain.com');
</script>
/* in getCookie.html */
<script>
window.addEventListener('message', function (e) {
if (e.origin === 'your.domain.com') {
var soughtCookie = /give me the cookie\:(.*)/.exec(e.data)[1];
// read the cookie
var cookie = getCookieFn(soughtCookie)
e.source.postMessage(cookie.toString(), 'your.domain.com');
}
}, false);
</script>
you could have a backend web service which shares the contents of the cookie with the 3rd party, but then your server would have to hold the cookie value in session and have a session id that is some how shared with the other website.
Can also special page and redirection so that the cookie value is read and passed to your domain as a form submit.
Lets say your domain is yours.com and on page yours.com/page1 you set some cookie value.
Now xyz.com , another domain wants that value. xyz.com/somePage, redirects to yours.com/spl (along with parameter of the page to send user to say xyz.com/somePage2), Now yours.com/spl gets the cookie via JavaScript and then redirects to xyz.com/somePage2 passing the cookie value as a POST or a GET parameter.
Full working sample at http://sel2in.com/pages/prog/html/acrossSites/make.php (with a simple web service)
AJAX not example wont work but can do it with iframes.
Code :
coki.js (goes on the first site that wants to expose cookies)
function setCookie(cname,cvalue, daysExpire)
{
var d = new Date();
d.setTime(d.getTime()+(daysExpire * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires + " ; path=/ ;"
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
wsa.php (goes on site 1). To make it more secure can check the calling page/ container URL and use a dynamic secret key.
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
error_reporting(E_WARNING);
$d = $_REQUEST['s'];
if($d != "secret565"){
echo "Bad secret bye";
return;
}
$n = $_REQUEST['n'];
if($n == ""){
echo "No cookie name, bye";
return;
}
?>
<script src=coki.js>
</script>
<script >
n = '<?php echo "$n"?>'
v = getCookie(n)
//alert("For " + n + ", got :" + v + ".")
window.parent.gotVal(n, v)
</script>
getc.html
Goes on site 2, gets the value of cookie C1 or other cookie from site 1 via wsa.php, using an iframe. wsa.php reads the secret auth key and cookie name from its parameters, then calls a javascript function in containing page to pass back values
<form name=f1 action=ws.php method=post>
<h1>Get cookie from Javascript sample </h1>
http://sel2in.com/pages/prog/html/acrossSites/
<table>
<tr><td>Url from <td/><td> <input name=u1 value='wsa.php' size=100><td/></tr>
<tr><td>Cookie Name <td/><td> <input name=n value='C1'><td/></tr>
<tr><td>Secret <td/><td> <input name=s value='secret565'><td/></tr>
<tr><td><input type=button value='Go' onclick='s1do()' > <td/><td><td/></tr>
</table>
</form>
<div id = result>result here</div>
<div id = cc1>container</div>
v 2 c
<script>
function gotVal(n, v){
document.getElementById("result").innerHTML = "For " + n + ", got :" + v + "."
}
function s1do(){
document.getElementById("cc1").innerHTML = ""
n1 = document.f1.n.value
s1 = document.f1.s.value
url = document.f1.u1.value
qry = "s=" + escape(s1) + "&n=" + escape(n1)
s = "<iframe border=0 height =1 width=1 src=\"" + url + "?" + qry + "\" ></iframe>"
document.getElementById("cc1").innerHTML = s
}
</script>

How to send an email from JavaScript

I want my website to have the ability to send an email without refreshing the page. So I want to use Javascript.
<form action="javascript:sendMail();" name="pmForm" id="pmForm" method="post">
Enter Friend's Email:
<input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:98%;" />
<input name="pmSubmit" type="submit" value="Invite" />
Here is how I want to call the function, but I'm not sure what to put into the javascript function. From the research I've done I found an example that uses the mailto method, but my understanding is that doesn't actually send directly from the site.
So my question is where can I find what to put inside the JavaScript function to send an email directly from the website.
function sendMail() {
/* ...code here... */
}
You can't send an email directly with javascript.
You can, however, open the user's mail client:
window.open('mailto:test#example.com');
There are also some parameters to pre-fill the subject and the body:
window.open('mailto:test#example.com?subject=subject&body=body');
Another solution would be to do an ajax call to your server, so that the server sends the email. Be careful not to allow anyone to send any email through your server.
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)
Directly From Client - Calling 3rd Party API - not recommended
in short:
register for Mailjet to get an API key and Secret
use fetch to call API to send an email
Like this -
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.
I couldn't find an answer that really satisfied the original question.
Mandrill is not desirable due to it's new pricing policy, plus it required a backend service if you wanted to keep your credentials safe.
It's often preferable to hide your email so you don't end up on any lists (the mailto solution exposes this issue, and isn't convenient for most users).
It's a hassle to set up sendMail or require a backend at all just to send an email.
I put together a simple free service that allows you to make a standard HTTP POST request to send an email. It's called PostMail, and you can simply post a form, use JavaScript or jQuery. When you sign up, it provides you with code that you can copy & paste into your website. Here are some examples:
JavaScript:
<form id="javascript_form">
<input type="text" name="subject" placeholder="Subject" />
<textarea name="text" placeholder="Message"></textarea>
<input type="submit" id="js_send" value="Send" />
</form>
<script>
//update this with your js_form selector
var form_id_js = "javascript_form";
var data_js = {
"access_token": "{your access token}" // sent after you sign up
};
function js_onSuccess() {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
}
function js_onError(error) {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
}
var sendButton = document.getElementById("js_send");
function js_send() {
sendButton.value='Sending…';
sendButton.disabled=true;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
js_onSuccess();
} else
if(request.readyState == 4) {
js_onError(request.response);
}
};
var subject = document.querySelector("#" + form_id_js + " [name='subject']").value;
var message = document.querySelector("#" + form_id_js + " [name='text']").value;
data_js['subject'] = subject;
data_js['text'] = message;
var params = toParams(data_js);
request.open("POST", "https://postmail.invotes.com/send", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
return false;
}
sendButton.onclick = js_send;
function toParams(data_js) {
var form_data = [];
for ( var key in data_js ) {
form_data.push(encodeURIComponent(key) + "=" + encodeURIComponent(data_js[key]));
}
return form_data.join("&");
}
var js_form = document.getElementById(form_id_js);
js_form.addEventListener("submit", function (e) {
e.preventDefault();
});
</script>
jQuery:
<form id="jquery_form">
<input type="text" name="subject" placeholder="Subject" />
<textarea name="text" placeholder="Message" ></textarea>
<input type="submit" name="send" value="Send" />
</form>
<script>
//update this with your $form selector
var form_id = "jquery_form";
var data = {
"access_token": "{your access token}" // sent after you sign up
};
function onSuccess() {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
}
function onError(error) {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
}
var sendButton = $("#" + form_id + " [name='send']");
function send() {
sendButton.val('Sending…');
sendButton.prop('disabled',true);
var subject = $("#" + form_id + " [name='subject']").val();
var message = $("#" + form_id + " [name='text']").val();
data['subject'] = subject;
data['text'] = message;
$.post('https://postmail.invotes.com/send',
data,
onSuccess
).fail(onError);
return false;
}
sendButton.on('click', send);
var $form = $("#" + form_id);
$form.submit(function( event ) {
event.preventDefault();
});
</script>
Again, in full disclosure, I created this service because I could not find a suitable answer.
I know I am wayyy too late to write an answer for this question but nevertheless I think this will be use for anybody who is thinking of sending emails out via javascript.
The first way I would suggest is using a callback to do this on the server. If you really want it to be handled using javascript folowing is what I recommend.
The easiest way I found was using smtpJs. A free library which can be used to send emails.
1.Include the script like below
<script src="https://smtpjs.com/v3/smtp.js"></script>
2. You can either send an email like this
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : 'them#website.com',
From : "you#isp.com",
Subject : "This is the subject",
Body : "And this is the body"
}).then(
message => alert(message)
);
Which is not advisable as it will display your password on the client side.Thus you can do the following which encrypt your SMTP credentials, and lock it to a single domain, and pass a secure token instead of the credentials instead.
Email.send({
SecureToken : "C973D7AD-F097-4B95-91F4-40ABC5567812",
To : 'them#website.com',
From : "you#isp.com",
Subject : "This is the subject",
Body : "And this is the body"
}).then(
message => alert(message)
);
Finally if you do not have a SMTP server you use an smtp relay service such as Elastic Email
Also here is the link to the official SmtpJS.com website where you can find all the example you need and the place where you can create your secure token.
I hope someone find this details useful. Happy coding.
You can find what to put inside the JavaScript function in this post.
function getAjax() {
try {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (try_again) {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
} catch (fail) {
return null;
}
}
function sendMail(to, subject) {
var rq = getAjax();
if (rq) {
// Success; attempt to use an Ajax request to a PHP script to send the e-mail
try {
rq.open('GET', 'sendmail.php?to=' + encodeURIComponent(to) + '&subject=' + encodeURIComponent(subject) + '&d=' + new Date().getTime().toString(), true);
rq.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 400) {
// The request failed; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
}
};
rq.send(null);
} catch (fail) {
// Failed to open the request; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
} else {
// Failed to create the request; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
}
Provide your own PHP (or whatever language) script to send the e-mail.
I am breaking the news to you. You CAN'T send an email with JavaScript per se.
Based on the context of the OP's question, my answer above does not hold true anymore as pointed out by #KennyEvitt in the comments. Looks like you can use JavaScript as an SMTP client.
However, I have not digged deeper to find out if it's secure & cross-browser compatible enough. So, I can neither encourage nor discourage you to use it. Use at your own risk.
There seems to be a new solution at the horizon. It's called EmailJS. They claim that no server code is needed. You can request an invitation.
Update August 2016: EmailJS seems to be live already. You can send up to 200 emails per month for free and it offers subscriptions for higher volumes.
window.open('mailto:test#example.com'); as above
does nothing to hide the "test#example.com" email address from being harvested by spambots. I used to constantly run into this problem.
var recipient="test";
var at = String.fromCharCode(64);
var dotcom="example.com";
var mail="mailto:";
window.open(mail+recipient+at+dotcom);
In your sendMail() function, add an ajax call to your backend, where you can implement this on the server side.
Javascript is client-side, you cannot email with Javascript. Browser recognizes maybe only mailto: and starts your default mail client.
JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:
send an email without refreshing the page
You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)
If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.
It seems like one 'answer' to this is to implement an SMPT client. See email.js for a JavaScript library with an SMTP client.
Here's the GitHub repo for the SMTP client. Based on the repo's README, it appears that various shims or polyfills may be required depending on the client browser, but overall it does certainly seem feasible (if not actually significantly accomplished), tho not in a way that's easily describable by even a reasonably-long answer here.
There is a combination service. You can combine the above listed solutions like mandrill with a service EmailJS, which can make the system more secure.
They have not yet started the service though.
Another way to send email from JavaScript, is to use directtomx.com as follows;
Email = {
Send : function (to,from,subject,body,apikey)
{
if (apikey == undefined)
{
apikey = Email.apikey;
}
var nocache= Math.floor((Math.random() * 1000000) + 1);
var strUrl = "http://directtomx.azurewebsites.net/mx.asmx/Send?";
strUrl += "apikey=" + apikey;
strUrl += "&from=" + from;
strUrl += "&to=" + to;
strUrl += "&subject=" + encodeURIComponent(subject);
strUrl += "&body=" + encodeURIComponent(body);
strUrl += "&cachebuster=" + nocache;
Email.addScript(strUrl);
},
apikey : "",
addScript : function(src){
var s = document.createElement( 'link' );
s.setAttribute( 'rel', 'stylesheet' );
s.setAttribute( 'type', 'text/xml' );
s.setAttribute( 'href', src);
document.body.appendChild( s );
}
};
Then call it from your page as follows;
window.onload = function(){
Email.apikey = "-- Your api key ---";
Email.Send("to#domain.com","from#domain.com","Sent","Worked!");
}
There is not a straight answer to your question as we can not send email only using javascript, but there are ways to use javascript to send emails for us:
1) using an api to and call the api via javascript to send the email for us, for example https://www.emailjs.com says that you can use such a code below to call their api after some setting:
var service_id = 'my_mandrill';
var template_id = 'feedback';
var template_params = {
name: 'John',
reply_email: 'john#doe.com',
message: 'This is awesome!'
};
emailjs.send(service_id,template_id,template_params);
2) create a backend code to send an email for you, you can use any backend framework to do it for you.
3) using something like:
window.open('mailto:me#http://stackoverflow.com/');
which will open your email application, this might get into blocked popup in your browser.
In general, sending an email is a server task, so should be done in backend languages, but we can use javascript to collect the data which is needed and send it to the server or api, also we can use third parities application and open them via the browser using javascript as mentioned above.
If and only if i had to use some js library, i would do that with SMTPJs library.It offers encryption to your credentials such as username, password etc.
The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:
Use Ajax to send request to the PHP script ,check that required field are not empty or incorrect using js also keep a record of mail send by whom from your server.
function sendMail() is good for doing that.
Check for any error caught while mailing from your script and take appropriate action.
For resolving it for example if the mail address is incorrect or mail is not send due to server problem or it's in queue in such condition report it to user immediately and prevent multi sending same email again and again.
Get response from your script Using jQuery GET and POST
$.get(URL,callback);
$.post(URL,callback);
Since these all are wonderful infos there's a little api called Mandrill to send mails from javascript and it works perfectly. You can give it a shot. Here's a little tutorial for the start.
Full AntiSpam version:
<div class="at">info<i class="fa fa-at"></i>google.com</div>
OR
<div class="at">info#google.com</div>
<style>
.at {
color: blue;
cursor: pointer;
}
.at:hover {
color: red;
}
</style>
<script>
const el33 = document.querySelector(".at");
el33.onclick = () => {
let recipient="info";
let at = String.fromCharCode(64);
let dotcom="google.com";
let mail="mailto:";
window.open(mail+recipient+at+dotcom);
}
</script>
Send an email using the JavaScript or jQuery
var ConvertedFileStream;
var g_recipient;
var g_subject;
var g_body;
var g_attachmentname;
function SendMailItem(p_recipient, p_subject, p_body, p_file, p_attachmentname, progressSymbol) {
// Email address of the recipient
g_recipient = p_recipient;
// Subject line of an email
g_subject = p_subject;
// Body description of an email
g_body = p_body;
// attachments of an email
g_attachmentname = p_attachmentname;
SendC360Email(g_recipient, g_subject, g_body, g_attachmentname);
}
function SendC360Email(g_recipient, g_subject, g_body, g_attachmentname) {
var flag = confirm('Would you like continue with email');
if (flag == true) {
try {
//p_file = g_attachmentname;
//var FileExtension = p_file.substring(p_file.lastIndexOf(".") + 1);
// FileExtension = FileExtension.toUpperCase();
//alert(FileExtension);
SendMailHere = true;
//if (FileExtension != "PDF") {
// if (confirm('Convert to PDF?')) {
// SendMailHere = false;
// }
//}
if (SendMailHere) {
var objO = new ActiveXObject('Outlook.Application');
var objNS = objO.GetNameSpace('MAPI');
var mItm = objO.CreateItem(0);
if (g_recipient.length > 0) {
mItm.To = g_recipient;
}
mItm.Subject = g_subject;
// if there is only one attachment
// p_file = g_attachmentname;
// mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);
// If there are multiple attachment files
//Split the files names
var arrFileName = g_attachmentname.split(";");
// alert(g_attachmentname);
//alert(arrFileName.length);
var mAts = mItm.Attachments;
for (var i = 0; i < arrFileName.length; i++)
{
//alert(arrFileName[i]);
p_file = arrFileName[i];
if (p_file.length > 0)
{
//mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);
mAts.add(p_file, i, g_body.length + 1, p_file);
}
}
mItm.Display();
mItm.Body = g_body;
mItm.GetInspector.WindowState = 2;
}
//hideProgressDiv();
} catch (e) {
//debugger;
//hideProgressDiv();
alert('Unable to send email. Please check the following: \n' +
'1. Microsoft Outlook is installed.\n' +
'2. In IE the SharePoint Site is trusted.\n' +
'3. In IE the setting for Initialize and Script ActiveX controls not marked as safe is Enabled in the Trusted zone.');
}
}
}

Categories

Resources