How do I set a cookie in iOS Phonegap? - javascript

I'm using the reddit API and can successfully login and receive a cookie value in return. The code I use is as follows
loginPost = $.ajax({
type: 'POST',
url: 'http://www.reddit.com/api/login/' + username + '?user=' + username + '&passwd=' + password + '&api_type=json',
xhrFields: {
withCredentials: true
},
dataType: "json",
success: function() {
console.log("Define response variables");
var header = loginPost.getAllResponseHeaders();
var responseText = loginPost.responseText;
var match = header.match(/(Set-Cookie|set-cookie): reddit_session=(.+?);/);
if (match) {
reddit_session = match[2];
window.localStorage.setItem("reddit_session", reddit_session);
window.localStorage.setItem("reddit_username", username);
window.localStorage.setItem("reddit_password", password);
console.log("Logged in!");
//alert(responseText);
$('.loginWrapper').slideUp('fast', function() {
$('#feedWrapper').css("top", "44px");
$('#feedWrapper').css("bottom", "0");
// Animation complete.
});
}
else {
reddit_session = null;
window.localStorage.setItem("reddit_session", null);
navigator.notification.alert('Your username or password is incorrect. Please try again.');
console.log("Login Failed");
}
},
});
I am storing the cookie using
var header = loginPost.getAllResponseHeaders();
var match = header.match(/(Set-Cookie|set-cookie): reddit_session=(.+?);/);
if(match){
reddit_session = match[2];
window.localStorage.setItem("reddit_session", reddit_session);
But the cookie isn't sent with a simple request to http://www.reddit.com/api/me.json. All that is returned is an empty JSON response like this {}. If I browse to that link in my browser (and am, of course, logged into reddit) it returns a JSON string with all the user data.
Any idea how I can store the cookie so that it is usable in a UIWebView?

Any idea how I can store the cookie so that it is usable in a UIWebView?
It appears that iOS cookies have been problematic since phonegap 2.5; please see [Handling cookies in PhoneGap/Cordova
I can't see any more current (phonegap 3.3) info [http://docs.phonegap.com/en/3.3.0/_index.html]

Related

Payment Navigation form php to payment gateway and back to php (response back to php page )

i created a login.php file where the user can will be navigated to instamojo payment page . After completing the transaction the user is getting the success message from instamojo , but i need to display the successful transaction in my domain or in own php file . so how can i get the transation related information to my webpage or to my login.php file
Ex: Redirecting from our login.php to instamojo(payment gateway)and response back (success message)to our login.php intimating the user that payment is success
var rootURL = "cgshealthcare.com/HealthCareSystem/";;
$(document).ready(function() {
$('#login').click(function() {
if ($('#username').val() == "" || $('#password').val() == "") {
alert("Please enter username or password");
return false;
}
cardloginUser($('#username').val(), $('#password').val());
});
});
function forwardtoRegister() {
window.location = "login.php?page=register";
}
function cardloginUser(userName, password) {
console.log('userName: ' + userName);
console.log('password: ' + password);
if (userName.length < 1) {
$('#errorlist').html("<font color='red'><b> Please enter User ID</b></font>");
return false;
}
if (password.length < 1) {
$('#errorlist').html(" <font color='red'><b> Please enter Password</b></font>");
return false;
}
console.log(rootURL + '/authenticate/' + userName + '/' + password);
$.ajax({
type: 'GET',
url: rootURL + '/authenticate/' + userName + '/' + password,
dataType: "json",
success: function(data) {
console.log("hello" + data.responseMessageDetails);
var list = data == null ? [] : (data.responseMessageDetails instanceof Array ? data.responseMessageDetails : [data.responseMessageDetails]);
console.log("List : " + list);
if ((list).length < 1) {
$('#errorlist').html("<font color='red'><b> Invalid User Name and Password Combination </b></font>");
$('#errorblock').css("visibility") == "visible";
}
$.each(list, function(index, responseMessageDetails) {
console.log("Status " + responseMessageDetails);
var message = responseMessageDetails.message;
if (message.indexOf("]:") > 0) message = message.substring(0, message.indexOf("]:") + 2);
console.log("message" + message);
console.log("USer Data" + responseMessageDetails.status);
console.log("USer Data" + responseMessageDetails.message);
if (responseMessageDetails.status == "Success") {
window.location = "imjo.in/NpKxN";;
} else if (responseMessageDetails.status == "Fail") {
window.location = "www.google.com";
console.log("Fail1");
$('#errorlist').html("<font color='red'><b>" + message + "</b></font>");
} else {
console.log("Fail111");
$('#errorlist').html("<font color='red'><b> We are sorry some intermittent Issue. Please try after some time. </b></font>");
}
});
},
error: function(data) {
console.log("data...." + data);
var list = data == null ? [] : (data.responseMessageDetails instanceof Array ? data.responseMessageDetails : [data.responseMessageDetails]);
console.log("data...." + data);
$.each(list, function(index, responseMessageDetails) {
console.log(responseMessageDetails);
var message = responseMessageDetails.message;
if (message.indexOf("]:") > 0) message = message.substring(0, message.indexOf("]:") + 2);
$('#errorlist').html("<font color='red'><b>" + message + "</b></font>");
});
}
});
}
function showLogin() {
window.location = "login.php";
}
Please look at the integration guide here.
After user enters payment information on instamojo, they are redirected to a redirect-url which you specify (and is a url on your website). Instamojo appends transaction results to this url. You can make it a php url on your website and read the results using GET method. Depending upon the results, you can process your payment and display results to the end-user. More on GET method here...
Instamojo also provides for webhooks, which are like silent POSTs in the background and can be used as backups in case redirect urls in front-end fail for some reason. This way if end-users' redirection failed for any reason, the webhook will still receive information in the background which can be used you to update your database for success/failure of transaction. Of course you webserver has to be up and running to receive webhooks notifications. If that's the point of failure, nothing will work :)
The API link I shared has all those details.
Thanks

Possibility to create another User while logged in

I'm creating a game using Parse.com as back-end. I want to create another user in Parse database while I'm still logged in. I'm using Parse user.signUp() method to register another user, since Parse.com provides it as a standard method for user registration. But I don't want the current user's session to expire. Currently, it works but as soon as another user is registered, the new user's session is directly logged in.
Here is the case for your information:
I want the user (e.g. myself here) to enter the email for user to invite other user to this game. When user enters email id, an email is sent actually (using PHP) and then the function creates a temporary user. For this I'm using the following code:
function inviteFriend() {
var email = $("#inviteEmail").val();
var pass = 'randomPass123';
var varData = 'email=' + email;
console.log(varData);
if (email != null) {
$.ajax({
type : 'POST',
url : './src/php.php',
data : varData,
success : function() {
alert("Invite sent successfully.");
var user = new Parse.User();
user.set("username", "tempUser");
user.set("password", pass);
user.set("email", email);
user.signUp(null, {
success : function(user) {
alert("User created successfully.");
console.debug(user);
},
error : function(user, error) {
console.log("LogIn error := " + error.message);
}
});
}
});
}
}
Please suggest any workarounds.

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.

Get LinkedIn Access Token with OAuthSimple in Javascript

I'm using OAuthSimple in Javascript with PIN based authentication (OOB flow).
We are developing an HTML5 app which lives inside a mobile device's native wrapper using PhoneGap. There's not ANY server side (no URL at all), all requests are sent using the mobile device as a proxy.
So far I managed to:
- Get Request Token
- Redirect user to authorization page
- Got authorization PIN
I need sample code that shows how to get an Access Token using OAuthSimple Javascript library.
Any help will be appreciated. Thanks!
Not sure if you are the same person who posted on our forums recently (see post here https://developer.linkedin.com/forum/oauthsimple-request-access-token), but I replied with demo code on how to do just that using OAuthSimple.
The actual sample code can be found here: https://gist.github.com/efc88a38da25ff4e9283
If you need any help using it, don't hesitate to reach out!
-Jeremy
This will create a phonegap linkedIn login, its just a worked around code though, but this works atleast for me
var consumer_key = "key";
var shared_secret = "secrete";
self.oauth = OAuthSimple(consumer_key, shared_secret); var linkedInScope = 'r_basicprofile r_emailaddress w_messages r_network';
var url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/requestToken", parameters: {scope: linkedInScope, oauth_callback: "oob"}}).signed_url;
var request = 'requestToken';
var linkedInObj = new Object;
function linkedInWorkAround(url,request,data){
var callType = 'GET';
var xhr = $.ajax({
url : url,
beforeSend : function(){
$.mobile.loading( 'show' );
if(request == 'linkedIn_login'){
callType = 'POST';
}
},
timeout : 8000,
data : data,
type : callType,
success: function(r){
$.mobile.loading( 'hide' );
if(request == 'requestToken'){
var oauthRes = r.split('&');
$.each(oauthRes, function(k,v){
var resObj = v.split('=')
linkedInObj[resObj[0]] = resObj[1];
});
url = 'https://www.linkedin.com/uas/oauth/authenticate?scope='+linkedInScope+'&oauth_token='+linkedInObj.oauth_token;
request = 'oauth_token';
linkedInWorkAround(url,request);
}
else if(request == 'oauth_token'){
var accessCode = $(r).find('.access-code');
if(accessCode.size()){
self.oauth.reset();
var pin = $(r).find('.access-code').text();
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {scope: linkedInScope, oauth_verifier: pin}, signatures: linkedInObj}).signed_url;
request = 'accessToken';
linkedInWorkAround(url,request);
}
else{
$('.custom-linkedIn').remove();
var cloneIn = $(r).find('form').addClass('custom-linkedIn').clone();
$('a,span,select,.duration-label,.access',cloneIn).hide();
$('#pageLinkedIn .errMsgHolder').after(cloneIn)
$('#session_key-oauthAuthorizeForm').textinput();
$('#session_password-oauthAuthorizeForm').textinput();
$('input[type=submit]').button();
$('form.custom-linkedIn').submit(function(){
$('.errMsgHolder').hide().text('');
url = 'https://www.linkedin.com/uas/oauth/authorize/submit';
request = 'linkedIn_login';
var data = $(this).serialize();
linkedInWorkAround(url,request,data);
return false;
});
}
}
else if(request == 'linkedIn_login'){
self.oauth.reset();
var pin = $(r).find('.access-code').text();
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {scope: linkedInScope, oauth_verifier: pin}, signatures: linkedInObj}).signed_url;
request = 'accessToken';
linkedInWorkAround(url,request);
}
else if(request == 'accessToken'){
var oauthRes = r.split('&');
self.oauth.reset();
$.each(oauthRes, function(k,v){
var resObj = v.split('=')
linkedInObj[resObj[0]] = resObj[1];
});
url = self.oauth.sign({action: "GET", path: "https://api.linkedin.com/v1/people/~/email-address", signatures: linkedInObj}).signed_url;
request = 'getResultLinkedIn';
linkedInWorkAround(url,request);
}
else if(request == 'getResultLinkedIn'){
$('body').css({opacity:0});
var userLIemail = ($('#session_key-oauthAuthorizeForm').size()) ? $('#session_key-oauthAuthorizeForm').val() : $(r).text();
}
},
error : function(a,b,c){
alert('err')
console.log(a,b,c)
self._cs(a)
$.mobile.loading( 'hide' );
if(a.statusText.toLowerCase() == 'unauthorized'){
$('.errMsgHolder').show().text('The email address or password you provided does not match our records');
}
}
})
}
linkedInWorkAround(url,request);

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