Почему OAuth2 с Gmail Nodejs Nodemailer создает ошибку имени пользователя и пароля не принимается

OAuth2 выдает ошибку «Имя пользователя и пароль не приняты» при попытке отправить электронное письмо с помощью Gmail + Nodejs + Nodemailer

Код - Nodejs - Nodemailer и xoauth2

var nodemailer = require("nodemailer");

var generator = require('xoauth2').createXOAuth2Generator({
    user: "", // Your gmail address.

    clientId: "",
    clientSecret: "",
    refreshToken: "",
});



// listen for token updates
// you probably want to store these to a db
generator.on('token', function(token){
    console.log('New token for %s: %s', token.user, token.accessToken);
});


// login
var smtpTransport = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        xoauth2: generator
    }
});


var mailOptions = {
    to: "",
    subject: 'Hello ', // Subject line
    text: 'Hello world ', // plaintext body
    html: '<b>Hello world </b>' // html body
};


smtpTransport.sendMail(mailOptions, function(error, info) {
  if (error) {
    console.log(error);
  } else {
    console.log('Message sent: ' + info.response);
  }
  smtpTransport.close();
});

вопросы:

  • Я использовал площадку Google OAuth2 для создания токенов, https://developers.google.com/oauthplayground/

  • Он пытается получить действительный токен доступа в порядке, используя refreshToken (т.е. он печатает новый токен доступа на экране). Ошибок нет, пока он не попытается отправить электронное письмо.

  • Я добавил необязательный токен доступа: но получил ту же ошибку. («Имя пользователя и пароль не приняты»)

  • Я не уверен на 100% насчет «имени пользователя», в документации говорится, что ему нужен «пользовательский» адрес электронной почты - я предполагаю, что адрес электронной почты учетной записи, созданной для токена, не на 100% ясен. Я пробовал несколько вещей, но ничего не помогло.

  • Я просмотрел параметры в учетных записях Gmail, но не нашел ничего неправильного.

  • Кроме того, когда я сделал это с Java, ему понадобился идентификатор пользователя google, а не адрес электронной почты, не знаю, почему он использует адрес электронной почты, а Java использует UserId.


person eddyparkinson    schedule 13.11.2014    source источник


Ответы (2)


nodemailer не работает с областью "составить"

Проблема заключалась в "размахе"

он не работает с: https://www.googleapis.com/auth/gmail.compose

но работает нормально, если я использую https://mail.google.com/

person eddyparkinson    schedule 14.11.2014
comment
Я столкнулся с аналогичной проблемой, даже если использую правильный объем. Знаете ли вы о какой-либо возможной проблеме, которая могла бы это вызвать? (Я объяснил свою проблему здесь: stackoverflow.com/questions/19766912/) - person Abdelrahman Shoman; 18.05.2017
comment
@ Abdel-RahmanShoman Я оставил проблему на "Nodemailer" на github - они сказали, что область видимости, которая устранила проблему для меня. - person eddyparkinson; 29.05.2017
comment
какой объем мы должны использовать? @eddyparkinson - person ngLover; 27.11.2018
comment
@ngLover см. значения области действия - Gmail API v1 - здесь developers.google.com/oauthplayground - person eddyparkinson; 30.11.2018
comment
то же самое произошло, когда я использовал только область отправки (googleapis.com/auth/gmail.send) использовал рекомендованный объем, и все прошло хорошо - person niCad; 28.12.2018
comment
Я использовал это руководство и предложил область действия только gmail.compose. Но с nodemailer это не сработало. С mail.google.com это работает. - person ivosh; 29.05.2019
comment
Вступайте сюда в 2020 году, и это все еще проблема. Действительно, требуется полный объем. Это действительно похоже на ошибку в реализации nodemailer - если мы отправляем только электронное письмо с ним, нам понадобится только область 'send', а не полная mail.google.com. - person fullStackChris; 10.08.2020

Просто сделайте следующее:

1- Получите файл credentials.json отсюда https://developers.google.com/gmail/api/quickstart/nodejs, нажмите включить Gmail API и выберите приложение для ПК.

2- Сохраните этот файл где-нибудь вместе с файлом учетных данных.

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://mail.google.com'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
    if(err){
        return console.log('Error loading client secret file:', err);
    }

    // Authorize the client with credentials, then call the Gmail API.
    authorize(JSON.parse(content), getAuth);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
    const {client_secret, client_id, redirect_uris} = credentials.installed;
    const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, (err, token) => {
        if(err){
            return getNewToken(oAuth2Client, callback);
        }
        oAuth2Client.setCredentials(JSON.parse(token));
        callback(oAuth2Client);
    });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */

function getNewToken(oAuth2Client, callback) {
    const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
    });
    console.log('Authorize this app by visiting this url:', authUrl);
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    rl.question('Enter the code from that page here: ', (code) => {
        rl.close();
        oAuth2Client.getToken(code, (err, token) => {
        if (err) return console.error('Error retrieving access token', err);
        oAuth2Client.setCredentials(token);
        // Store the token to disk for later program executions
        fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
            if (err) return console.error(err);
            console.log('Token stored to', TOKEN_PATH);
        });
        callback(oAuth2Client);
        });
    });
}

function getAuth(auth){

}

3 - Запустите этот файл, набрав в своем терминале: node THIS_FILE.js

4- У вас будет файл token.json

5- возьмите информацию о пользователе из credentials.json и token.json и заполните их следующей функцией

const nodemailer = require('nodemailer');
        const { google } = require("googleapis");
        const OAuth2 = google.auth.OAuth2;

        const email = 'gmail email'
        const clientId = ''
        const clientSecret = ''
        const refresh = ''



        const oauth2Client = new OAuth2(
            clientId,
            clientSecret,
        );

        oauth2Client.setCredentials({
            refresh_token: refresh
        });
        const newAccessToken = oauth2Client.getAccessToken()


        let transporter = nodemailer.createTransport(
            {
                service: 'Gmail',
                auth: {
                    type: 'OAuth2',
                    user: email,
                    clientId: clientId,
                    clientSecret: clientSecret,
                    refreshToken: refresh,
                    accessToken: newAccessToken
                }
            },
            {
                // default message fields

                // sender info
                from: 'Firstname Lastname <your gmail email>'
            }
        );

        const mailOptions = {
            from: email,
            to: "",
            subject: "Node.js Email with Secure OAuth",
            generateTextFromHTML: true,
            html: "<b>test</b>"
        };

        transporter.sendMail(mailOptions, (error, response) => {
            error ? console.log(error) : console.log(response);
            transporter.close();
        });

person Adam    schedule 25.05.2020