无法从服务帐户发送电子邮件,收到 400 前提条件检查失败错误

问题描述 投票:0回答:1

尝试使用我的项目中角色所有者的服务帐户发送电子邮件。我不断收到 400 错误,提示前提条件检查失败。

const sendEmail = async () => {

const auth = new google.auth.GoogleAuth({
    keyFile: "gmail.json", //the key file
    scopes: "https://www.googleapis.com/auth/gmail.send",
});

const authClientObject = await auth.getClient();
const gmail = google.gmail({version:"v1", auth: authClientObject})
  // Compose the email
  const email = 'To: [email protected]\r\n' +
                `Cc: [email protected]\r\n` +
                'Subject: CUSTOM DONATION ALERT\r\n\r\n' +
                'blablabla\r\n';
  
  // Encode the email in base64 format
  const base64EncodedEmail = Buffer.from(email).toString('base64');
  
  // Send the email
  gmail.users.messages.send({
    userId: serviceAccountEmail,
    resource: {
      raw: base64EncodedEmail,
    },
  }, (err, res) => {
    if (err) {
      console.error('Error sending email:', err);
      return;
    }
  
    console.log('Email sent:', res.data);
  });

}

node.js google-api gmail
1个回答
0
投票

前提条件检查失败。

通常在您使用服务帐户且未在 Google Workspace 帐户中正确配置域范围委派时发生。

我还可以看到您没有指出服务帐户应指定为工作区帐户中的哪个用户。

var sendMessage = gmail.users.messages.send({
    auth: jwtClient,
    userId: '<user to impersonate>',
    resource: {
      raw: raw
    }
  }, (err, res) => {
     if (err) {
       console.error(err);
     } else {
       console.log(res);
     }
 });
© www.soinside.com 2019 - 2024. All rights reserved.