使用 Firebase 函数通过 Gmail API 发送电子邮件

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

我正在尝试创建一个名为

sendEmail
的 Firebase 函数,它能够通过我的 Google Workspace 电子邮件帐户发送电子邮件。我可以通过以下方式调用此功能:

const sendEmailFn = httpsCallable(functions, 'sendEmail');
const response = await sendEmailFn({ email, subject, message });

index.js
文件中函数的代码如下所示:

const functions = require("firebase-functions");
const {google} = require("googleapis");

const oAuth2Client = new google.auth.OAuth2(
    process.env.CLIENT_ID,
    process.env.CLIENT_SECRET,
    process.env.CALLBACK_URL,
);

const gmailClient = new google.gmail({
  version: "v1",
  auth: oAuth2Client,
});

// Firebase Cloud Function to send an email
exports.sendEmail = functions.https.onCall(async (data, context) => {
  const {email, subject, message} = data;

  // Construct the email content
  const emailContent = `
    From: "Sender Name" <[email protected]>
    To: "Recipient Name" <${email}>
    Subject: ${subject}
    Content-Type: text/html; charset=utf-8

    ${message}
  `;

  try {
    // Send the email using the Gmail API
    await gmailClient.users.messages.send({
      userId: "me",
      requestBody: {
        raw: Buffer.from(emailContent).toString("base64"),
      },
    });

    return {success: true};
  } catch (error) {
    console.error("Error sending email:", error);
    throw new functions.https.HttpsError(
        "internal",
        "An error occurred while sending the email.",
    );
  }
});

按上面定义的方式调用此函数时,日志提示以下错误:

我收到发送电子邮件时出错:错误:未设置访问权限、刷新令牌、API 密钥或刷新处理程序回调。

将 API 密钥设置为

oAuth2Client
时,例如:

oAuth2Client.setCredentials({
  // Set your API key as the access token
  access_token: "YOUR_API_KEY",
});

我得到错误:

消息:'无效凭证'

此外,当不使用

oAuth2Client
并直接在
gmail.auth
中设置API-Key时,API调用被调用,但是有一个
401 Response
.

在 Google 控制台的 Gmail-API 设置中,无法添加此类 API 密钥,因此仅显示

OAuth 2.0 Client IDs
Service Accounts
并允许使用此 API。

那么我如何正确使用

oAuth2Client
使用带有 Firebase 函数的 React 应用程序从我的 Google Workspace 帐户发送电子邮件。

编辑1: 当以下列方式使用服务帐户时:

// Create an OAuth2 client using the service account credentials
const authClient = new google.auth.JWT({
  email: keyFile.client_email,
  key: keyFile.private_key,
  scopes: ["https://www.googleapis.com/auth/gmail.send", "https://www.googleapis.com/auth/gmail.readonly"],
});

// Set the credentials on the OAuth2 client
authClient.authorize((err, tokens) => {
  if (err) {
    console.error("Error authenticating:", err);
    throw new Error("Failed to authenticate");
  } else {
    console.log("Authentication successful");
  }
});

我现在可以进行身份验证了,但是现在出现了另一个错误:

代码:400,消息:'先决条件检查失败。'

反应是问题吗,我应该换成

me
以外的东西?我已经尝试了这段代码中的所有内容:

const response = await gmailClient.users.messages.send({
  userId: "me",
  requestBody: createMessage,
});
reactjs firebase google-cloud-functions google-oauth gmail-api
© www.soinside.com 2019 - 2024. All rights reserved.