使用GmailAPI将标签添加到从Nodemailer发送的Gmail

o8x7eapl  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(303)

我正在使用Gmail API,使用nodemailer向未读线程发送自动电子邮件。我想在Gamil中添加一个AutoResponse标签,以便回复的邮件显示该标签。
这是发送邮件的代码

const checkForNewMessages = () => {
    //get message details
  gmail.users.messages.list(
    {
      userId: "me",
      q: `is:unread`,
    },
    async (err, res) => {
      if (err) return console.log("The API returned an error: " + err);

      const messages = res.data.messages;

      if (messages?.length) {
        console.log("New message received!");

        //checking if message unread
        for (const message of messages) {
          const messageDetails = await gmail.users.messages.get({
            userId: "me",
            id: message.id,
          });
          const threadId = messageDetails.data.threadId;
          const threadDetails = await gmail.users.threads.get({
            userId: "me",
            id: threadId,
          });

          const addLabelToThread = await gmail.users.threads.modify({
            userId: "me",
            id: threadId,
            resource: {
              addLabelIds: ["AutoResponse"],
              removeLabelIds: ["INBOX"],
            },
          });

          if (
            !threadDetails.data.messages.some(
              (msg) =>
                msg.labelIds.includes("SENT") &&
                msg.payload.headers.find(
                  (header) =>
                    header.name === "From" &&
                    header.value.includes("mymail@gmail.com")
                )
            )
          ) {
            console.log(
              `New email thread with subject "${
                messageDetails.data.payload.headers.find(
                  (header) => header.name === "Subject"
                ).value
              }" and thread ID ${threadId} received!`
            );

            // Sending a response to new unread Threads
            const transporter = nodemailer.createTransport({
              service: "gmail",
              auth: {
                type: "OAuth2",
                user: "mymail@gmail.com",
                clientId: process.env.CLIENT_ID,
                clientSecret: process.env.CLIENT_SECRET,
                refreshToken: process.env.REFRESH_TOKEN,
                accessToken: oAuth2Client.getAccessToken(),
              },
            });

            const mailOptions = {
              from: "mymail@gmail.com",
              to: messageDetails.data.payload.headers.find(
                (header) => header.name === "From"
              ).value,
              subject:
                "Re: " +
                messageDetails.data.payload.headers.find(
                  (header) => header.name === "Subject"
                ).value,
              text: "Thank you for your message. I will respond as soon as I am available",
            };

            transporter.sendMail(mailOptions, async (err, info) => {
              if (err) {
                console.log(err);
              } else {
                console.log(
                  `Automatic response sent to ${
                    messageDetails.data.payload.headers.find(
                      (header) => header.name === "From"
                    ).value
                  }: ${info.response}`
                );
                addLabelToThread();
              }
            });

          } else {
            console.log(
              `Email thread with thread ID ${threadId} already has a reply from you.`
            );
          }
        }
      } else {
        console.log("No new messages.");
      }
    }
  );
};

我尝试了addLabelToThread函数,但似乎不起作用。将此错误指定为特定错误

error: {
        code: 400,
        message: 'Invalid label: SENT',
        errors: [
          {
            message: 'Invalid label: SENT',
            domain: 'global',
            reason: 'invalidArgument'
          }
        ],
        status: 'INVALID_ARGUMENT'
      }
kq0g1dla

kq0g1dla1#

我有一个解决办法。建议的解决方案使用GMAIL Node.js SDK实现。

观察-

每当我们使用send()函数发送新电子邮件时,默认情况下会添加一个SENT标签。
当我们尝试使用modify()删除它时,它将抛出一个错误,如

{
      message: 'Invalid label: SENT',
      domain: 'global',
      reason: 'invalidArgument'
 }

因此,要在已发送的电子邮件中附加新标签,我们可以在发送电子邮件后执行以下代码。

const updatedGmail = await gmail.users.messages.modify({
        userId: "me", // if user is authenticated
        id: res.data.id, // id of email
        requestBody: {
            addLabelIds: ["Label_5091976681185583145"]
        }
    })

这将添加另一个标签到已发送的电子邮件与SENT标签。虽然,这不是大多数人想要的方式,但我这样做了,它对我很有效

相关问题