I am new to node.js programming .I am using nodemailer module for sending emails.
const nodemailer = require ('nodemailer'),
credentials=require('./credentials.js');
var mailTransport=nodemailer.createTransport({
service:'Gmail',
auth: {
user : credentials.gmail.user,
pass : credentials.gmail.password,
}
});
function sendMail(mail_id){
mailTransport.sendMail({
from: ' "my name" <myname#gmail.com>',
to : mail_id, //user#gmail.com
subject : 'Hello',
text: "Hello How do u do ?",
},function(err,info){
if(err){
console.log('Unable to send the mail :'+err.message);
}
else{
console.log('Message response : '+info.response);
}
});
}
exports.sendMail=sendMail;
This is my program for sending emails to different users. But I am getting Invalid Login . I don't have any idea why this is coming . I am new to node.js and server side scripting.
I am using my gmail username and password for credentials.
Please help me.
One reason could be the 'modern security standard' protection from Gmail.
Check you gmail inbox for any new mail having subject "Google Account: sign-in attempt blocked"
If yes, open the mail and click on the link https://www.google.com/settings/security/lesssecureapps
set 'Access for less secure apps' to 'Turn on'. Try again, it should be working now.
Particularly 2 issues: or you don't have enabled Less Secure Apps https://myaccount.google.com/lesssecureapps or you don't have enabled Display Unlock Captcha https://accounts.google.com/DisplayUnlockCaptcha, you need to turn on both of them.
U need to Enable Security for Apps :
|*| If u r using gmail,
Use :
service: 'gmail',
Goto :
https://myaccount.google.com/lesssecureapps
Enable :
Allow less secure apps: ON
|*| If u r using yahoo,
Use :
service: 'yahoo',
Goto :
https://login.yahoo.com/account/security
Enable :
Allow apps that use less secure sign in
|*| If u r using Live or Hotmail, No need to enable anything.
Use :
service: 'hotmail',
Did you double-check your login credentials? Also did you double-check your "from" adress to match your email?
I used the nodemailer for some tests 3 weeks ago with the gmail example given on the github page and it worked like a charm:
https://github.com/andris9/Nodemailer
Invalid login indicates mistyped/wrong credentials.
In my case,
turning on less secure apps only was not enough: https://myaccount.google.com/lesssecureapps
I had to enable display unlock captcha also: https://accounts.google.com/DisplayUnlockCaptcha
This solved my issue and i was able to send emails using nodemail and gmail.
This thing is not random actually nodemailer community site itself says to perform the second step to enable captcha, if turning on the less secure apps do not work alone.
https://community.nodemailer.com/using-gmail/
Above image is taken from the nodemailer article link i have shared.
Adding this as a separate answer, since the accepted answer no longer works.
Since May 30, 2022, Google no longer supports less secure apps. There is a nodemailer GitHub issue on this (https://github.com/nodemailer/nodemailer/issues/1424) with the updated steps:
Go to https://myaccount.google.com/security
Enable 2FA
Create App Password for Email
Copy that password (16 characters) into the pass parameter in Nodemailer auth.
...,
auth: {
user: 'yourmail#gmail.com',
pass: 'your_new_app_password',
},
...
if you have a workspace user account you may need to, as an admin:
Create a user group
Add the user to that group
Go to the user group settings and enable unsecure apps under Security so that other groups emails won't be affected
If that isn't enough (this worked for me after everything was fine for months with first three steps), go to myaccount.google.com and log in with the specific user email and password, go to Security again and turn on less secure apps.
Related
I have endpoints coded in Nodejs... I use the following codes to keep them safe...
const corsOption = {
origin: ['https://www.mywebsite.com'],
};
app.use(cors(corsOption));
if (host !== "myendpoint.com") {
return res.status(403).json({ message: "forbidden access" });
}
will these keep my endpoints safe... or do I have to do anything more for my endpoints to keep them safe... I don't want bots or anyone else to use it... I know that they are public but I want to restrict access... pls, any help or suggestion ???
thank you
To be sure you can control who can access your endpoint, you can setup a token authentication.
When you send a request to your endpoint, the header should include:
Authorization: Token {your token}
And in your endpoint, you can check if the token is authorized or not (by storing authorized token in a database). If the token is not recognized, you can send back a 403 error.
If your website accesses your endpoints, this means that any browser that can display your website must also be able to access your endpoints. Requests are not made by your website, they are made by browsers visiting your website.
You must first ask how much you want to restrict access:
Restrict to individual known users to whom you send a password via mail, which they must then type into your website ("log on") before they can make any requests to your endpoints.
Restrict to users who have self-registered. Can anyone in the world then self-register, or do you demand confirmation via an email address?
Restrict to users who can log on with their Google (or Facebook, or ...) account.
Zain_Ul_Din's answer shows details of a possible implementation for the "self-registration" case. See also What's the best way to add social login (Sign in with Google) to existing email/password app and database?
you can implement user authentication and authorization in your Node js app to restrict access.
for this you can use the jsonwebtoken npm package.
Look up John Smilga's node and express projects on google for a 10hr video including 4 projects. One of the projects introduces JSON web tokens and how to use them.I highly recommend that.
You can also use the express-rate-limit package. With this you should be able to 'limit' how many requests a user can make to your API endpoints within a set amount of time. If the requests exceed that limit then this middleware steps in and stops further access (Haven't tested it in production myself but looks good)
Sending an email using NodeMailer & Gmail
Google has reported that after May 30 third party apps cannot use username and password for signing in. Does this affect nodemailer. We usually allow less secure APP in the gsuit gmail setting before using it in nodemailer.
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#address.com',
pass: 'yourpassword'
}
});
It would help if you generated an app password to use nodemailer.
First, you need to turn on two-factor-authentication.
And then in your manage account go to security.
You can see the app password below two-step verification.
Go to app password select app other and write custom app name (example project name) and click on generate.
You get a password use that password instead of your mail password.
I've been digging all over for this. Their docs are pretty woeful about the change. Found this, not definitive...I'm in the "set up app password let's see if it still works" camp.
Note the reply "Second, yes, the best information we have is that App Passwords will continue to work."
https://support.google.com/mail/thread/157808790/will-imap-work-after-may-30th?hl=en
I had the same issue and solved it.
Follow these steps:
1)Go to the google account security section
2) turn on 2-step verification under "singing in" to google (else 3rd step is not possible)
3) under signing in to google you will find App passwords, click it
4) select the "select app" and click custom app
5) Type any name of your choice and generate a password.
Now use the same email account and instead of your real password use the generated password.
For my Project i currently check the users (username & password) against an Active Directory so once i check that the user credentials are correct but im asking to see if is possible to log the user in to the system to see (#login_required) views for example
Is this something is possible as per my requirements I am not allowed to store passwords in the Django Admin page
Thanks in Advance
That is certainly possible, you just need to use a different authentication backend.
django-auth-ldap should do the job:
pip install django-auth-ldap
Now set it as the authentication backend:
# settings.py
AUTHENTICATION_BACKENDS = [
'django_auth_ldap.backend.LDAPBackend',
]
AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"
There are many more configuration options to be found in the docs:
https://django-auth-ldap.readthedocs.io/en/latest/
I have been having this issue for the past couple of weeks, it works every time locally, however once I deploy it to my heroku server, it will give me an invalid login error. I have gone into the account and givin access to less secure apps. And the credentials are correct, and it works on localhost every time. Is there something I am missing?
quickSendMail: function(routeBody, callback) {
//configuring the nodemailer for email notifications
var smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'mysmtpemail123',
pass: '******'
}
};
var mailOptions = {
from: 'SageStorm Site <mysmtpemail123#gmail.com>',
to: ['my email'],
subject: routeBody.subject,
html: 'my message'
};
var transporter = nodemailer.createTransport(smtpConfig);
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('server is ready to send emails');
}
})
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
return callback(err, null);
} else {
console.log('Message sent: ' + info.response);
return callback(null, info);
}
})
}
You can allow machines to access your gmail remotely using this link, but keep in mind that Google will affect your default account (even if you are connected with another one).
The easy way: use a incognito / private window (to have no google account connected) and log in your google account and then use the link above.
If that doesn't work try updating your nodemailer to the latest version.
According to https://support.google.com/accounts/answer/6009563, Go to https://accounts.google.com/b/0/DisplayUnlockCaptcha and allow access and try again ..
Also according to docs at nodemailer (https://github.com/nodemailer/nodemailer#delivering-bulk-mail)
I'm having issues with Gmail Gmail either works well or it does not
work at all. It is probably easier to switch to an alternative service
instead of fixing issues with Gmail. If Gmail does not work for you
then don't use it.
I set a bounty to this question, but after looking through the Nodemailer docs/Github, it seems that using Gmail will only lead to headaches.
According to the Nodemailer docs...
"...Gmail expects the user to be an actual user not a robot so it runs a lot of heuristics for every login attempt and blocks anything that looks suspicious to defend the user from account hijacking attempts.
For example you might run into trouble if your server is in another geographical location – everything works in your dev machine but messages are blocked in production."
I believe the second thing was my issue; my Nodemailer ran without issue on my machine, but immediately failed when I pushed the app to Heroku.
As for a fix, my only fix was to use a different email provider. All email accounts I've tried using have been fully authorized to allow other sign-ins and less safe apps; I've gone through every method Google has to offer to allow usage of the account, and I fully believe that it's simply not possible to get consistent results with Nodemailer and Gmail.
Using Outlook/Hotmail worked for me. I also tried switching to a different Gmail account. It worked successfully a couple times, then returned to the previous state.
Most times when one ends up with this kinda error from Nodemailer, one of these options listed by Google gets to fix it, take your time to go through the google account to be used has the required setting.
Google has listed all the potential problems and fixes for us. In as much as you turned on less secure apps setting. Be sure you are applying these to the correct account.
Step 1: Check your password
If you have these problems or can’t sign in, first check to make sure you’re using the right password.
Step 2: Try these troubleshooting steps
If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.
Sign in to your account from the web version of Gmail at https://mail.google.com. Once you’re signed in, try signing in to the mail app again.
Visit Display Unlock Captcha and sign in with your Gmail username and password. If asked, enter the letters in the distorted picture.
Your app might not support the latest security standards. Try changing a few settings to allow less secure apps access to your account.
Make sure your mail app isn't set to check for new email too often. If your mail app checks for new messages more than once every 10 minutes, the app’s access to your account could be blocked.
I am currently developing a dashboard with Google Analytics API, which will be accessible website back office. I realized this during this developing javaScript I block on 2 things:
The first is the authentication must be transparent to the user via the use of a token.
In my approach I utlise OAuth2 of the API by generating a token with the playground for this token to be valid
I join my code
gapi.analytics.ready(function() {
var CLIENT_ID = 'XXXX.apps.googleusercontent.com';
var CLIENT_SECRET ='XXX...';
var ACCESS_TOKEN = 'XXX...';
var REFRESH_TOKEN ='XXXX....';
var EXPIRE_IN ='3600';
var TOKEN_TYPE ='Bearer';
var ACCESS_TYPE ='offline';
var SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
gapi.analytics.auth.authorize({
clientid: CLIENT_ID,
client_secret:CLIENT_SECRET,
serverAuth: {
access_token: ACCESS_TOKEN,
refresh_token: REFRESH_TOKEN,
//token_type: TOKEN_TYPE,
//expires_in: EXPIRE_IN,
//access_type: ACCESS_TYPE,
}
});
After the validity of the data are more accessible with a 401 error (logical because the token is no longer valid)
or to my first question about how to obtain a valid token all the time?
My second question concerns the recovery of data I based on the recovery of the profile number (like many such works).
However SEVERAL of my sites using the tracking number (UA-XXXXXXXX-N).
Knowing that sites use this number is the posibility to find the profilId thanks to the tracking number and accountId that lion can deduct.
But I do not know how to arive.
Es that someone already out how to make this relationship ???
Pending your answers thank you in advance
(Sorry for the translation I utlise google translation)
Authenticating using the playground is a bad idea, and wont work for long. You are going to have to code your own authentication process here. It sounds like you want to do this with your own websites this your own data, I would normally recommend you use a service account. A service account can be set up to authenticate without requiring the user to do anything. While some people say that you can use a Service account with JavaScript, I don't feel that it is a secure solution, I also wonder if it is ok to do this under the current terms of service. So my first recommendation to you is to look into using as service account with a server sided scripting language. say PHP. If you don't a user will have to authenticate and then they will only be seeing the information on there own website not your website.
Second how to find the Profile id:
The first and probably easiest option would be to just go to the admin section of Google analytics and find your profile id there. If you are looking for a way of doing this programmatically you, I would use the account summaries report from the Management API this will give you a list of all of the accounts for the current authenticated user you can then scan that to find the profile ids you want.