Archive Gmail Messages
Archive messages by removing them from inbox (not deleting)
Source Code
import fs from "fs";
const [messageIdsArg = "", outputPath = "session/archive-results.json"] =
process.argv.slice(2);
const messageIds = messageIdsArg
.split(",")
.map((id) => id.trim())
.filter(Boolean);
if (messageIds.length === 0) {
console.error("No message IDs provided");
console.log(JSON.stringify({ success: false, error: "no_message_ids" }));
process.exit(1);
}
console.log(`Archiving ${messageIds.length} message(s)...`);
/**
* Archive messages using Gmail batch modify API
* Archives by removing INBOX label (messages stay in All Mail)
*/
async function archiveMessages(ids) {
const BATCH_SIZE = 50;
const results = { archived: [], failed: [] };
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
const batch = ids.slice(i, i + BATCH_SIZE);
const res = await fetch(
"https://gmail.googleapis.com/gmail/v1/users/me/messages/batchModify",
{
method: "POST",
headers: {
Authorization: "Bearer PLACEHOLDER_TOKEN",
"Content-Type": "application/json",
},
body: JSON.stringify({
ids: batch,
removeLabelIds: ["INBOX"],
}),
}
);
if (res.ok) {
results.archived.push(...batch);
console.log(` Archived ${results.archived.length}/${ids.length}...`);
} else {
const errorText = await res.text();
console.error(`Batch failed: ${res.status} - ${errorText}`);
results.failed.push(...batch);
}
}
return results;
}
try {
const results = await archiveMessages(messageIds);
// Write results
const dir = outputPath.split("/").slice(0, -1).join("/");
if (dir) fs.mkdirSync(dir, { recursive: true });
const output = {
success: results.failed.length === 0,
archivedAt: new Date().toISOString(),
archivedCount: results.archived.length,
failedCount: results.failed.length,
archived: results.archived,
failed: results.failed,
};
fs.writeFileSync(outputPath, JSON.stringify(output, null, 2));
console.log(`\nā Archived ${results.archived.length} message(s)`);
if (results.failed.length > 0) {
console.log(`ā Failed to archive ${results.failed.length} message(s)`);
}
console.log(JSON.stringify(output));
} catch (error) {
console.error("Archive failed:", error.message);
throw error;
}