email-triage
Morning voice inbox briefing — fetch, prioritize, reply, and archive emails from R1 without looking at a screen
- License 许可
- MIT
- 最近更新
- 2026-09-04
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- email-triage
- author
- rabbit-r1-skillz
- version
- 1.0.0
- description
- Morning voice inbox briefing — fetch, prioritize, reply, and archive emails from R1 without looking at a screen
02 资源文件 3
- 资产文件card.jpg20.0 KB
- 资产文件icon.png10.9 KB
- 参考文档index.html47.4 KB
03 SKILL.md 正文
EmailTriage — OpenClaw Skill
EmailTriage uses your local machine as the mail backend for voice-driven inbox management on the R1. The skill connects to Gmail (or IMAP), fetches your unread emails, has an LLM flag urgency, and handles send/archive/batch commands dispatched from the R1 app.
How it works
- R1 opens and sends
fetch_inboxto this skill via the OpenClaw shared-storage bridge - The skill fetches unread emails, runs LLM urgency classification, and returns a prioritized list
- R1 announces the count and reads summaries aloud — you scroll and tap with one hand
- Dictated replies are sent via
send_reply; archive, skip, and star commands viabatch_action - Handled email IDs are persisted in R1 storage so the app stays in sync across sessions
Prerequisites
Required
- Node.js 20+ on your local machine
- OpenClaw CLI installed and running (
openclaw serve) - An Anthropic API key for urgency classification (or OpenAI key)
- A Gmail account with OAuth2 credentials configured (see step 2), or an IMAP/SMTP server
Optional
- Nodemailer for SMTP-based sending (included in deps)
- node-imap for non-Gmail IMAP accounts
- Gmail API via
googleapis(recommended — faster and no IMAP needed)
Local setup
1. Install dependencies
cd ~/.openclaw/skills/email-triage
npm install @anthropic-ai/sdk googleapis nodemailer dotenv
2. Configure Gmail OAuth2
Follow the Gmail API Quickstart to create OAuth2 credentials:
- Create a project in Google Cloud Console
- Enable the Gmail API
- Create OAuth2 credentials (Desktop app type)
- Run the one-time auth flow to generate a refresh token:
node auth-setup.js
Where auth-setup.js is the standard OAuth2 token exchange script — see the Gmail API quickstart linked above.
3. Configure environment
Create ~/.openclaw/skills/email-triage/.env:
# Required — LLM for urgency classification
ANTHROPIC_API_KEY=sk-ant-...
# Gmail OAuth2 (recommended)
GMAIL_CLIENT_ID=...apps.googleusercontent.com
GMAIL_CLIENT_SECRET=...
GMAIL_REFRESH_TOKEN=...
GMAIL_USER=you@gmail.com
# Alternative: IMAP/SMTP (if not using Gmail API)
IMAP_HOST=imap.example.com
IMAP_PORT=993
IMAP_USER=you@example.com
IMAP_PASS=yourpassword
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=you@example.com
SMTP_PASS=yourpassword
# Optional — use OpenAI instead of Anthropic
OPENAI_API_KEY=sk-...
# Tuning
MAX_EMAILS=20
FETCH_DAYS=1
4. Register the skill
Add to ~/.openclaw/openclaw.config.json:
{
"skills": [
{
"name": "email-triage",
"path": "~/.openclaw/skills/email-triage/skill.js",
"description": "Morning voice inbox — fetch, prioritize, reply, archive via R1"
}
]
}
5. Create the skill file
Create ~/.openclaw/skills/email-triage/skill.js:
"use strict";
require("dotenv").config({ path: __dirname + "/.env" });
const { google } = require("googleapis");
const Anthropic = require("@anthropic-ai/sdk");
const nodemailer = require("nodemailer");
const MAX_EMAILS = parseInt(process.env.MAX_EMAILS || "20", 10);
const FETCH_DAYS = parseInt(process.env.FETCH_DAYS || "1", 10);
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
// ── Gmail client ───────────────────────────────────────────
function getGmailClient() {
const auth = new google.auth.OAuth2(
process.env.GMAIL_CLIENT_ID,
process.env.GMAIL_CLIENT_SECRET
);
auth.setCredentials({ refresh_token: process.env.GMAIL_REFRESH_TOKEN });
return google.gmail({ version: "v1", auth });
}
// ── Entry point ────────────────────────────────────────────
module.exports = async function emailTriage(command, params, storage) {
switch (command) {
case "fetch_inbox": return fetchInbox();
case "send_reply": return sendReply(params);
case "batch_action": return batchAction(params);
default:
return { error: `Unknown command: ${command}` };
}
};
// ── FETCH INBOX ────────────────────────────────────────────
async function fetchInbox() {
try {
const gmail = getGmailClient();
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() - FETCH_DAYS);
const after = Math.floor(cutoff.getTime() / 1000);
const listResp = await gmail.users.messages.list({
userId: "me",
q: `is:unread after:${after}`,
maxResults: MAX_EMAILS,
});
const messageList = listResp.data.messages || [];
if (messageList.length === 0) {
return { emails: [] };
}
const rawEmails = await Promise.all(
messageList.map(m => fetchMessage(gmail, m.id))
);
const filtered = rawEmails.filter(Boolean);
const emails = await classifyUrgency(filtered);
// Sort: urgent first, then today, then normal
emails.sort((a, b) => {
const rank = { urgent: 0, today: 1, normal: 2 };
return (rank[a.urgency] ?? 2) - (rank[b.urgency] ?? 2);
});
return { emails };
} catch (err) {
console.error("fetch_inbox error:", err.message);
return { error: err.message };
}
}
async function fetchMessage(gmail, id) {
try {
const msg = await gmail.users.messages.get({ userId: "me", id, format: "full" });
const headers = msg.data.payload?.headers || [];
const get = name => headers.find(h => h.name.toLowerCase() === name)?.value || "";
const sender = parseSenderName(get("from"));
const senderEmail = parseSenderEmail(get("from"));
const subject = get("subject") || "(no subject)";
const date = get("date");
const snippet = msg.data.snippet || "";
const body = extractBody(msg.data.payload);
const time = formatEmailTime(date);
return { id, sender, senderEmail, subject, snippet, body, time, urgency: "normal" };
} catch (err) {
console.error("fetchMessage error:", id, err.message);
return null;
}
}
function parseSenderName(from) {
const match = from.match(/^([^<]+)</);
return match ? match[1].trim().replace(/^"|"$/g, "") : from.split("@")[0];
}
function parseSenderEmail(from) {
const match = from.match(/<([^>]+)>/);
return match ? match[1] : from;
}
function extractBody(payload) {
if (!payload) return "";
const tryDecode = data => {
try { return Buffer.from(data, "base64").toString("utf-8"); } catch (_) { return ""; }
};
if (payload.mimeType === "text/plain" && payload.body?.data) {
return tryDecode(payload.body.data).slice(0, 1200);
}
if (payload.parts) {
for (const part of payload.parts) {
if (part.mimeType === "text/plain" && part.body?.data) {
return tryDecode(part.body.data).slice(0, 1200);
}
}
// Fall back to HTML part stripped of tags
for (const part of payload.parts) {
if (part.mimeType === "text/html" && part.body?.data) {
const html = tryDecode(part.body.data);
return html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 1200);
}
}
}
return payload.body?.data ? tryDecode(payload.body.data).slice(0, 1200) : "";
}
function formatEmailTime(dateStr) {
if (!dateStr) return "";
const d = new Date(dateStr);
if (isNaN(d.getTime())) return "";
const now = new Date();
const isToday = d.toDateString() === now.toDateString();
return isToday
? d.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" })
: d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}
// ── URGENCY CLASSIFICATION ─────────────────────────────────
async function classifyUrgency(emails) {
if (emails.length === 0) return emails;
const today = new Date().toDateString();
const summaries = emails.map((e, i) =>
`${i}: From: ${e.sender} | Subject: ${e.subject} | Snippet: ${e.snippet.slice(0, 120)}`
).join("\n");
const prompt = `You are an email urgency classifier. Today is ${today}.
For each email, return one of three urgency levels:
- "urgent": Requires a response or action today — deadlines, direct questions from people you know, time-sensitive requests, calendar conflicts
- "today": Should be reviewed today but not immediately — project updates, FYIs, newsletters with today-specific content
- "normal": Can wait — newsletters, marketing, automated notifications, CC'd threads, GitHub notifications
Classify these emails and return a JSON array of objects with fields "index" (number) and "urgency" (string).
Return only valid JSON, no other text.
Emails:
${summaries}`;
try {
const msg = await anthropic.messages.create({
model: "claude-haiku-4-5-20251001",
max_tokens: 512,
messages: [{ role: "user", content: prompt }],
});
const text = msg.content[0]?.text?.trim() || "[]";
const parsed = JSON.parse(text);
if (Array.isArray(parsed)) {
parsed.forEach(({ index, urgency }) => {
if (emails[index] && ["urgent", "today", "normal"].includes(urgency)) {
emails[index].urgency = urgency;
}
});
}
} catch (err) {
console.error("classifyUrgency error:", err.message);
// Non-fatal — emails keep urgency "normal"
}
return emails;
}
// ── SEND REPLY ─────────────────────────────────────────────
async function sendReply(params) {
const { emailId, body, subject } = params;
if (!body || !emailId) {
return { error: "Missing emailId or body" };
}
try {
const gmail = getGmailClient();
const original = await gmail.users.messages.get({ userId: "me", id: emailId, format: "metadata" });
const headers = original.data.payload?.headers || [];
const get = name => headers.find(h => h.name.toLowerCase() === name)?.value || "";
const to = parseSenderEmail(get("from"));
const threadId = original.data.threadId;
const messageId = get("message-id");
const rawMessage = [
`From: ${process.env.GMAIL_USER}`,
`To: ${to}`,
`Subject: ${subject || "Re: " + get("subject")}`,
`In-Reply-To: ${messageId}`,
`References: ${messageId}`,
"Content-Type: text/plain; charset=utf-8",
"",
body,
].join("\r\n");
const encoded = Buffer.from(rawMessage).toString("base64url");
await gmail.users.messages.send({
userId: "me",
requestBody: { raw: encoded, threadId },
});
// Archive (move to All Mail, remove INBOX label)
await gmail.users.messages.modify({
userId: "me",
id: emailId,
requestBody: { removeLabelIds: ["INBOX", "UNREAD"] },
});
return { ok: true, confirmation: "Reply sent and email archived." };
} catch (err) {
console.error("send_reply error:", err.message);
return { error: err.message };
}
}
// ── BATCH ACTIONS ──────────────────────────────────────────
async function batchAction(params) {
const { action, emailIds = [], params: actionParams = {} } = params;
try {
const gmail = getGmailClient();
switch (action) {
case "archive_skipped":
case "archive_newsletters":
case "mark_all_read": {
const removals = action === "mark_all_read"
? ["UNREAD"]
: ["INBOX", "UNREAD"];
await Promise.all(
emailIds.map(id =>
gmail.users.messages.modify({
userId: "me",
id,
requestBody: { removeLabelIds: removals },
})
)
);
const verb = action === "mark_all_read" ? "marked read" : "archived";
return {
ok: true,
confirmation: `${emailIds.length} email${emailIds.length !== 1 ? "s" : ""} ${verb}.`,
};
}
case "star_sender": {
await Promise.all(
emailIds.map(id =>
gmail.users.messages.modify({
userId: "me",
id,
requestBody: { addLabelIds: ["STARRED"] },
})
)
);
return {
ok: true,
confirmation: `Starred ${emailIds.length} email${emailIds.length !== 1 ? "s" : ""} from ${actionParams.senderName || "sender"}.`,
};
}
case "filter_priority":
// Archive everything not from priority senders (done locally on R1, no-op here)
return { ok: true, confirmation: "Priority filter applied." };
default:
return { error: `Unknown batch action: ${action}` };
}
} catch (err) {
console.error("batch_action error:", err.message);
return { error: err.message };
}
}
6. Start OpenClaw
openclaw serve
You should see email-triage listed in the registered skills output.
Command reference
fetch_inbox
Sent on app open. No params required.
Response:
| Field | Type | Description |
|---|---|---|
emails |
array | Prioritized email objects (see below) |
error |
string|null | Error message if fetch failed |
Email object:
| Field | Type | Description |
|---|---|---|
id |
string | Gmail message ID |
sender |
string | Display name |
senderEmail |
string | Email address |
subject |
string | Email subject |
snippet |
string | Short preview text |
body |
string | Full plain-text body (up to 1200 chars) |
urgency |
"urgent" | "today" | "normal" |
LLM-classified priority |
time |
string | Human-readable receive time |
send_reply
Sent when the user confirms a dictated reply.
| Field | Type | Description |
|---|---|---|
emailId |
string | Gmail message ID being replied to |
body |
string | Dictated reply text |
subject |
string | Reply subject (prefixed with Re:) |
Response:
| Field | Type | Description |
|---|---|---|
ok |
boolean | True if send succeeded |
confirmation |
string | Human-readable confirmation for TTS |
error |
string|null | Error if failed |
batch_action
Sent when the user selects and confirms a batch operation.
| Field | Type | Description |
|---|---|---|
action |
string | One of archive_skipped, archive_newsletters, star_sender, mark_all_read, filter_priority |
emailIds |
string[] | IDs to act on |
params |
object | Action-specific params (e.g. {senderEmail, senderName} for star_sender) |
Response:
| Field | Type | Description |
|---|---|---|
ok |
boolean | True if action succeeded |
confirmation |
string | Spoken confirmation text |
error |
string|null | Error if failed |
Urgency classification logic
The skill uses claude-haiku-4-5-20251001 to classify each email as urgent, today, or normal based on sender, subject, and snippet. Classification is batch-processed in a single API call for all emails in the fetch. Failures are non-fatal — emails default to normal urgency.
Urgent signals: deadlines, direct questions, calendar invites, meeting requests, "ASAP", "today", "by EOD", replies from known contacts.
Today signals: project updates, newsletters with time-sensitive content, FYI threads you are directly addressed in.
Normal signals: marketing, automated notifications, GitHub/Jira bot messages, CC'd threads, newsletters.
Troubleshooting
R1 shows "Connection failed" on open
- Confirm
openclaw serveis running on the same network as the R1 - Check that the skill is registered in
openclaw.config.json - Verify your
.envfile is in~/.openclaw/skills/email-triage/
Red LED immediately — no emails loaded
- The Gmail OAuth2 refresh token may have expired — re-run
auth-setup.js - Confirm the Gmail API is enabled for your project in Google Cloud Console
- Check
GMAIL_USERmatches the authenticated account
Urgency classification always "normal"
- Verify
ANTHROPIC_API_KEYis valid and has quota - Check the Haiku model ID (
claude-haiku-4-5-20251001) is correct for your account - Switch to
claude-sonnet-4-6for more accurate classification on complex inboxes
Send reply fails
- Confirm the refresh token has
gmail.sendscope (requires re-auth if it was created without it) - Check that the original message ID exists and has not been permanently deleted
Batch archive does nothing
- Verify the R1 app is passing the correct
emailIdsarray - Gmail API requires
gmail.modifyscope — re-run auth if the token predates that scope
Security notes
- OAuth2 refresh tokens grant full Gmail access. Store
.envsecurely and never commit it to version control. - The skill runs only on your local machine. Email content is sent only to the Anthropic API for urgency classification (snippet + subject, not full body). Full email bodies are sent to the R1 for reading aloud but never to any third party.
- OpenClaw communicates over localhost by default. Do not expose the OpenClaw port to the internet without authentication.
- Reply templates and priority sender lists are stored in R1 on-device storage only — they do not leave the device.
04 同仓库更多 Skills
whisper-quiz
WhisperQuiz — voice-answered trivia game for Rabbit R1. Generates questions via the R1's built-in LLM, captures spoken answers via STT, and evaluates correctness with flexible LLM-based matching.
walk-cast
Walking podcast production skill. Receives raw audio metadata and transcript from the R1, removes long pauses, applies noise reduction and normalization, generates AI chapter titles and episode metadata via LLM, and uploads the final episode to your configured podcast RSS host (Spotify for Podcasters / Anchor, Podbean, Buzzsprout, RSS.com, or any FTP-accessible feed).
voice-novel
Local machine skill for VoiceNovel — handles story export to disk.
voice-guide
Environment description and navigation assistant for blind and low-vision users. Analyzes camera frames via a vision LLM, reads visible text, identifies scene categories (people/vehicles/food/hazards/exits), performs 360° scans, retrieves GPS position, and sends emergency SMS alerts — all via audio feedback with zero screen dependency.
voice-draft
Voice-driven document drafting for the Rabbit R1. Dictate stream-of-consciousness speech; the R1 formats it into Email, Blog Post, Report, Proposal, Meeting Notes, Creative Writing, Code Comments, Cover Letter, or Tweet Thread — then saves the result to a configured folder on your local machine via OpenClaw.
voice-commit
Hands-free git and CI workflow voice controller for the Rabbit R1. Speak git/CI commands and hear results — commit, push, status, PR management, test runs, and deploy, all voice-driven via OpenClaw.