通过服务帐户

时间:2018-06-06 11:06:02

标签: jwt google-oauth2 nodemailer

我想要实现的是通过nodemailer从我的Web应用程序通过服务帐户向收件人发送邮件。

我从以下链接中获取了参考资料

  1. https://developers.google.com/identity/protocols/OAuth2ServiceAccount
  2. https://gypsyshen.com/2018/03/01/secure-gmail-access-with-oauth2-and-2lo-in-express/
  3. https://nodemailer.com/smtp/oauth2/
  4. 以下是代码:

    var express = require('express');
    var router = express.Router();
    var nodemailer = require('nodemailer');
    var {google} = require('googleapis');
    var serviceKey = require('../key/serviceKey.json');
    
    router.post('/', function(req, res, next){
      var jwtClient = new google.auth.JWT(serviceKey.client_email, null, serviceKey.private_key, ['https://mail.google.com'], null);
    
      jwtClient.authorize(function(error, token){
        if(error){
          console.log('Error: ' + error);
          res.json({success: false, error: error});
          return;
        }
    
        console.log('JWT Authorisation Success');
    
        var transporter = nodemailer.createTransport({
          host : 'smtp.gmail.com',
          port : 465,
          secure : true,
          auth : {
            type : 'OAuth2',
            user : serviceKey.client_email,
            serviceClient : serviceKey.client_id,
            privateKey : serviceKey.private_key,
            accessToken : token.access_token,
            expires : token.expiry_date
          }
        });
    
        var requestBody = req.body;
        var data = requestBody['data'];    
    
        var msg = "Data: "+data;
    
        transporter.sendMail({
          from: serviceKey.client_email,
          to: recipient@abc.com,
          subject : 'Test Mail',
          text : msg
        }, function(error, info){
            if(error){
              console.log("Error: "+error);
            } else {
              console.log("Success: "+info);
            }
        });
    
    
      });
    });
    
    module.exports = router;
    

    现在我遇到的问题是 - 虽然Console记录了消息“JWT授权成功”,但是当它实际发送邮件时,我收到此错误

      

    错误:登录无效:535-5.7.8不接受用户名和密码。   在535 5.7.8了解更多信息   https://support.google.com/mail/?p=BadCredentials v5-v6sm24994162pfd.1    - gsmtp

    我无法找到解决方法。请帮忙,并建议一些很好的资源来了解它。

    其他信息:服务帐户的角色设置为“服务帐户用户”

0 个答案:

没有答案