我在 Nextjs 15 中使用 Gmail,我可以获取所有电子邮件、发送电子邮件,但我的回复有问题。当我回复邮件时,在我的邮件对话中,我可以获取以前的每封邮件,这很好。但收件人收到一封新邮件。不在我们的同一个对话中
这是我的代码
import { google } from 'googleapis';
export async function POST(req) {
const { threadId, messageId, to, replyText, accessToken, from } = await req.json();
const auth = new google.auth.OAuth2();
auth.setCredentials({ access_token: accessToken });
const gmail = google.gmail({ version: 'v1', auth });
const rawMessage = [
`From: ${from}`,
`To: ${to}`,
`In-Reply-To: ${messageId}`,
`References: ${messageId}`,
`MIME-Version: 1.0`,
`Content-Type: text/plain; charset=UTF-8`,
``,
replyText,
].join('\n');
const encodedMessage = Buffer.from(rawMessage).toString('base64');
try {
const res = await gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: encodedMessage,
threadId: threadId,
},
})
.then((r) => {console.log(r)})
.catch((err) => { console.log(err) });
return new Response(JSON.stringify({ status: 'Reply sent successfully' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}
我尝试控制台记录所有内容,一切都很好。 我应该 await gmail.users.messages.send 添加一些字段或其他内容,以便我的收件人可以在同一对话邮件中 请帮助我。
我希望收件人和我在同一封对话邮件中。我在对话中回复的邮件,但收件人收到了新邮件
更改:包装messageID,显式传递threadID,添加base64编码
import { google } from 'googleapis';
export async function POST(req) {
const { threadId, messageId, to, replyText, accessToken, from } = await req.json();
const auth = new google.auth.OAuth2();
auth.setCredentials({ access_token: accessToken });
const gmail = google.gmail({ version: 'v1', auth });
const rawMessage = [
`From: ${from}`,
`To: ${to}`,
`Subject: Re: Your Subject Here`, // including the subject
`In-Reply-To: <${messageId}>`, // add angle brackets to prevent from detecting as plain text
`References: <${messageId}>`,
`MIME-Version: 1.0`,
`Content-Type: text/plain; charset=UTF-8`,
``,
replyText,
].join('\n');
const encodedMessage = Buffer.from(rawMessage)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
try {
await gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: encodedMessage,
threadId: threadId, // to ensure msg belongs to correct thread
},
});
return new Response(JSON.stringify({ status: 'Reply sent successfully' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}