مكتبة الأوامر الذكية
البرمجة

سكرتير الايميلات

ملخص تلقائي للبريد الالكتروني عن طريق الذكاء الاصطناعي

نص الأمر
const ANTHROPIC_API_KEY = "your-anthropic-api-key-here";
const MY_EMAIL = Session.getActiveUser().getEmail();

function runEmailAgent() {
  const threads = GmailApp.search("is:unread", 0, 100);

  if (!threads.length) {
    Logger.log("No unread emails. Done.");
    return;
  }

  const emailList = threads.map(thread => {
    const msg = thread.getMessages()[0];
    return [
      "From: " + msg.getFrom(),
      "Subject: " + msg.getSubject(),
      "Date: " + msg.getDate(),
      "Preview: " + msg.getPlainBody().slice(0, 300)
    ].join("\n");
  }).join("\n\n---\n\n");

  threads.forEach(t => t.markRead());
  Logger.log("Emails fetched and marked as read. Count: " + threads.length);

  let summary;
  try {
    const response = UrlFetchApp.fetch("https://api.anthropic.com/v1/messages", {
      method: "POST",
      headers: {
        "x-api-key": ANTHROPIC_API_KEY,
        "anthropic-version": "2023-06-01",
        "Content-Type": "application/json"
      },
      payload: JSON.stringify({
        model: "claude-sonnet-4-20250514",
        max_tokens: 1500,
        messages: [{
          role: "user",
          content: `You are my personal email assistant. Analyze these ${threads.length} unread emails and give me:

1. A short overall summary (2-3 sentences)
2. A bullet list of key emails worth knowing about
3. A "Required Actions" section — only if there are actual action items, deadlines, or replies needed. Skip entirely if nothing requires action.

Be concise. Plain text, no markdown.

Emails:
${emailList}`
        }]
      })
    });

    Logger.log("API status: " + response.getResponseCode());
    summary = JSON.parse(response.getContentText()).content[0].text;

  } catch (e) {
    Logger.log("API call failed: " + e.message);
    GmailApp.sendEmail(MY_EMAIL, "Email Agent Error", "Claude API call failed: " + e.message);
    return;
  }

  GmailApp.sendEmail(
    MY_EMAIL,
    ` Email digest — ${threads.length} emails (${new Date().toLocaleDateString()})`,
    summary
  );

  Logger.log("Digest sent successfully.");
}