[英]Adding Label to Gmail sent from Nodemailer with GmailAPI
I am using Gmail API, with nodemailer to send an automated email to unread threads.我正在使用 Gmail API,nodemailer 将自动发送 email 到未读线程。 I want to add a label of AutoResponse in Gamil so that the replied mails appear with that labels.
我想在 Gamil 中添加一个 label 的自动回复,以便回复的邮件显示带有该标签。
Here is the code for sending the mail这是发送邮件的代码
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.");
}
}
);
};
I tried the addLabelToThread function, but doesn't seem to work.我尝试了 addLabelToThread function,但似乎不起作用。 Giving this error to be specific
给出这个错误是具体的
error: {
code: 400,
message: 'Invalid label: SENT',
errors: [
{
message: 'Invalid label: SENT',
domain: 'global',
reason: 'invalidArgument'
}
],
status: 'INVALID_ARGUMENT'
}
I have a workaround for this.我有一个解决方法。 The proposed solution is implemented using
GMAIL Node.js SDK
.建议的解决方案是使用
GMAIL Node.js SDK
实现的。
Observation -观察-
Whenever we send new email using send()
function, it by default adds a SENT
Label to it.每当我们使用
send()
function 发送新的 email 时,它默认会向其添加一个SENT
Label。
When we try to remove it using modify()
it will throw an error such as当我们尝试使用
modify()
删除它时,它会抛出一个错误,例如
{
message: 'Invalid label: SENT',
domain: 'global',
reason: 'invalidArgument'
}
So, for attaching a new label to a sent email we can execute following code just after we sent the email.因此,为了将新的 label 附加到已发送的 email,我们可以在发送 email 后立即执行以下代码。
const updatedGmail = await gmail.users.messages.modify({
userId: "me", // if user is authenticated
id: res.data.id, // id of email
requestBody: {
addLabelIds: ["Label_5091976681185583145"]
}
})
This will add another label to sent email with SENT
label. Although, this is not the way most people want it but I did it this way and it works for me这将添加另一个 label 到发送 email 和
SENT
label。虽然,这不是大多数人想要的方式,但我这样做了,它对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.