Create an App Password for Gmail account and use in Service Suite script to login to account with 2FA enabled
-
Login to your Gmail account and create an App Password.
-
To Create an App Password:
-
Go to your Google Account.
-
Select Security.
-
Under "Signing in to Google," select App Passwords. You may need to sign in. If you don’t have this option, it might be because:
-
2-Step Verification is not set up for your account.
-
2-Step Verification is only set up for security keys.
-
Your account is through work, school, or other organization.
-
You turned on Advanced Protection.
-
-
-
Navigate to: https://myaccount.google.com/apppasswords
-
Select the app drop down and choose Other. Select the device drop down and choose Windows Computer.
-
Click Generate. An app password will be generated.
Use this app Password in-service suite script instead of the original password.
Example Code Snippet:
const IMAP_SERVER = "imap.gmail.com";
const SUBJECT = "Your MyAccount security code";
const EMAIL ="example@gmail.com";
const APP_PASSWORD ="juyyefjismupgqwf" ;
//
// To generate the APP_PASSWORD need to enable 2FA authentication in your google account
// and then generate the APP_PASSWORD at https://myaccount.google.com/apppasswords
//
function getCode(body) {
return body.match(/\d+/g)[0];
}
var mailClient = createMailClient(IMAP_SERVER, EMAIL, APP_PASSWORD, "IMAP");
mailClient.login();
try {
var lastUnread = mailClient.getLastUnreadMessages(1);
if (lastUnread.length > 0) {
var subject = lastUnread.get(0).getSubject();
if (subject.contains(SUBJECT)){
code = getCode(lastUnread.get(0).getBody());
log(code);
locker.put("THE_CODE",code); // PUTS CODE IN THELOCKER TO SHARE WITH DS SCRIPT
} else {
log("Last unread message do not match the expected subject: "+subject);
}
} else {
log("There are no new email messages in account "+EMAIL)
}
} catch(e) {
log(e.message)
} finally {
mailClient.logout();
}