How to send email using Javascript in a simplest way? - javascript

I'm doing the final project in my XML & JavaScript course and I'm having trouble with sending email via JavaScript.
I found this page: http://smtpjs.com/. But it requires SMTP credentials, I don't know what SMTP credentials is.
Who has used smtpjs.com or who has the solution please help me.
P/s: Do I need to upload my code to a host to send email. I always open html file from my computer, I wonder whether it will be able to send email or not.

First of all, I don't think you should run your code from the html file. You run it from a server to properly communicate with smtp.js
You can try this:
$('#form-submit').click(function () {
submitForm();
});
function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
if (name == "") {
alert('Invalid Name');
return;
}
if (message == "") {
alert('Message cannot be empty');
return;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(email)) {
alert('Invalid Email');
return;
}
Email.send("from#email.com",
"to#email.com",
"Message from " + name + " " + email,
message,
{
token: "63cb3a19-2684-44fa-b76f-debf422d8b00",
callback: function done(message) { alert("sent") }
});
}
I also used smtpjs and sendgrid.
I hope this helps.

If you want to send an email in javascript, you should turn on allow secure app access in Gmail.
Google will not let you send emails if you do not turn on allow the less secure app in Gmail.
Here is the link to:
Turn On Allow Secure App Access
Please note if you turn on the function in google, it is easy for attackers to find information about your Gmail account.
It is recommended to create an account just for development.

SMTP is the server that handles mails. Here is google's: 'smtp.gmail.com'.
You can directly send an e-mail from javascript. I suggest you go for JSON.

Related

firebase-ui for email verification

I've set up Firebase email/password authentication successfully using firebase-ui.
var uiConfig = {
signInSuccessUrl: '<?php echo $url; ?>',
signInOptions: [
// Leave the lines as is for the providers you want to offer your users.
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID
],
// Terms of service url.
tosUrl: '<your-tos-url>'
};
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);
but for security reasons I want the user to confirm her/his email.But fromthe above code it doesn't send a verfication mail to user.
So I've used following method to send a verification mail to user if he/she not verified his/her account mail.
firebase.auth().onAuthStateChanged(function(user) {
if (user && user.uid != currentUid) {
if (firebase.auth().currentUser.emailVerified) {
currentUid = user.uid;
else {
//---- HERE YOU SEND THE EMAIL
firebase.auth().currentUser.sendEmailVerification();
}
But when I used this code it sends multiple verification mails for same account. Which means this method runs each time a user reload the page. It would be really greatful if someone could help me to identify whether verification mail sent or not for a specific user using firebase.
I found what seems to be a better answer to this barely-documented (for JavaScript) Firebase issue in the sample code here:
// FirebaseUI config.
var uiConfig = {
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
var user = authResult.user;
...
if (authResult.additionalUserInfo.isNewUser)
{
console.log("new signin");
user.sendEmailVerification();
}
...
return true;
},
enjoy!
I'm late but if someone finds it like me:
if(currentUser.metadata.creationTime === currentUser.metadata.lastSignInTime)
Is true when it is a new user, so you have to send the verification email.
You can also do it within signInSuccess, no need to look on onAuthStateChanged
You could use SignInSuccessWithAuthResult callback to send email verification. What you need to do is provide a callback function and check if the user has verified email, if not, sendEmailVerification.

login using angular js and $http request not working

I want to login using $http and GET of REST web services. What I am doing is:
Taking data on the basis of username and password using $http.get
Storing the result: $scope.getResult=res;
Storing it in some variable:
var result=$scope.getResult;
var username=result.userName;
var password=result.password;
var user=this.user;
var pass=this.pass;
After that I will compare with the ng-model of username and password. If it is successful then it will redirect to another page like below:
if (username == user && password == pass)
{
window.location="/next.html";
}
Below is my complete code and please suggest the changes required in my case.
$scope.login = function () {
var user = this.user ; // ng-model of username in html page
var pass = this.pass; //ng-model of password in html page
$http.get("http://localhost:17681/api/userRegisters"+user+pass).success(function (res) {
$scope.getResult = res;
var result = $scope.getResult;
var username = result.userName;
var password = result.password;
if (username == user && password == pass) {
window.location="/next.html";
}
}
}
Please tell me how should I change my code in order to do that.
Thanks in advance :)
Replace the raw window.location method with the AngularJS $location service. Calling window.location from inside a $q service fulfillment handler will generally result in an AngularJS internal error.
$http.get("http://localhost:17681/api/userRegisters"+user+pass)
.then(function onFulfilled(response) {
$scope.getResult = response.data;
var result = $scope.getResult;
var username = result.userName;
var password = result.password;
if (username == user && password == pass) {
//Use this
$location.path("/next.html");
//Not this
//window.location="/next.html";
}
}).catch ( function onRejected(response) {
console.log(response.status);
});
For more information, see AngularJS $location Service API Reference.
Deprecation Notice
The $http legacy promise methods .success and .error have been deprecated. Use the standard .then method instead.1
Debugging the Response
Its gives record via response.data but doesnt give column records. what should be done in order to fetch data ?
What is the specification for the server side API?
What is the server side code that generates the response data?
These are things readers will need to know in order to help you. Otherwise any answer is just a guess.
Industry best practice is to avoid sending passwords as a parameter of a URL as that has security issues.
Two resources recommended by the AngularJS team:2
Deal with users authentication in an AngularJS web app
Authentication in Single Page Applications With Angular.js
Additional Resources
GitHub AngularJS Authentication
Bit of Tech: AngularJS Token Authentication
AngularJS User Registration and Login Example & Tutorial
"http://localhost:17681/api/userRegisters?username= " + username + "&password=" + password
and read the username and password from http://localhost:17681/api/userRegisters this location by using GET HTTP METHOD

JavaScript persist a search query through out the whole site

I'm currently fetching a query (e.g, http://localhost:49781/HTML/index.html?inputName=Marcus) from a html form using this following JavaScript:
function setSignedName() {
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
document.getElementById("signed_in_name").innerHTML += split[1];
} else {
document.getElementById("signed_in_name").innerHTML = "Not signed in";
}
running the script will get the result: Marcus.
I want this string to be persisted through out my site, so when the user navigates to another page the inputName will still be Marcus.
What is the best way of achieving this?
Edit: This approach is only for display/non-production use, I know using a server side language like PHP is the best approach.
I believe the best way is using localStorage. It works in all major browsers and it's easy to use:
function setSignedName() {
var userName = "";
if (window.location.search.indexOf("=") >= 0) {
var split = window.location.search.split("=");
userName += split[1];
} else {
userName = "Not signed in";
}
document.getElementById("signed_in_name").innerHTML = userName;
localStorage.setItem("userName", userName);
}
To access it:
var userName = localStorage.getItem("userName");
And this is it. Check for it in the Resources tab in Developer tools(F12) in your fav broswer.
You'll want to either repopulate it through GET parameters in your server side language, or if you want to hack it together, use a cookie and repopulate it with JavaScript on page load with "pushState".
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState()_method

Nodejs bcrypt library

I use the nodejs bcrypt library for better password protection.
I am not sure i understand exactly how to use it, but i got this so far:
//A module containing this login function:
login: function(credentials,req,res) {
//"credentials" is containing email and password from login form
var query = 'SELECT password, email FROM users WHERE email = ? LIMIT 1';
client.query(query,[credentials.email], function(err, results) {
if (results[0]) {
//Compare passwords
if (bcrypt.compareSync(credentials.password, results[0].password)) {
//Set session data and redirect to restricted area
}
}
});
}
I removed all the error handling here in the example so that its easier to read the code.
1.This works and i am able to login and set the session. But is this all there is to it? Am i missing something?
2.Looks like the salt is prepended to the password when generating hash. Dont I have to save the salt in db?
Any help appreciated
Yes, this is all there is to it! The salt you generate when encrypting the password originally is used to prevent against rainbow table attacks; you do not need to persist it.

Sending mail using CDO JavaScript error - Server is undefined

I got this code to send email using SMTP server, I tried many configuration of it that I found online, also VBscript similar code, and non of it is working.
I want to focus on this code, when I'm opening the HTA I'm getting error in line 8, says 'Server is undefined', What should I do to define it?
var cdoConfig = Server.CreateObject("CDO.Configuration");
cdoConfig.Fields("cdoSMTPServerName") = "194.90.9.22";
var cdoMessage = Server.CreateObject("CDO.Message");
cdoMessage.Configuration = cdoConfig;
var cdoBodyPart = cdoMessage.BodyPart;
cdoMessage.To = "aaa#gmail.com";
cdoMessage.From = "xxx#ddd.com";
cdoMessage.Subject = "CDO Test in JScript";
cdoMessage.TextBody = "This is a test email sent using JScript.";
cdoMessage.send();
Thanks,
Rotem
Jan, you should see that code uses "Server" (VBS), is it recommended ¿?
You may check this:
Your server(running the code) is not allowed to send (mail forwarding).
Auth, .Item(cdoSMTPAuthenticate) = cdoAnonymous, you should see if there's some auth on your mail server.
Hope this helps,
sorry for the delayed response looks like instead of using the server ip you need to spicify the server address for example smptout.secureserver.net but replace with your smpt address also most smtp server require username and password you will need to define these in your code.
in vbs it would be defined like so
Set emailConfig = emailObj.Configuration
emailConfig.Fields("smtpserver") = "your smtp address"
emailConfig.Fields("smtpserverport") = your smpt port
emailConfig.Fields("sendusing")= 2
emailConfig.Fields("smtpauthenticate") = 1
emailConfig.Fields("smtpusessl") = true/false "used for ssl"
emailConfig.Fields("sendusername") = "your smtp username"
emailConfig.Fields("sendpassword") = "your smtp password"
emailConfig.Fields.Update
i do not know js very well so i am unable to convert the vbs code to work in js. i hope this is some help

Categories