Skip to main content
Glama

get_recent_emails

Retrieve recent emails from the past few days with configurable date range and quantity limits for efficient email management.

Instructions

获取最近三天的邮件列表

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNo返回邮件数量限制(默认20)
daysNo获取最近几天的邮件(默认3天)

Implementation Reference

  • Primary handler function for the 'get_recent_emails' tool. Parses arguments, detects the email provider based on configuration, and delegates to either IMAP or POP3 specific implementations.
    async getRecentEmails(args = {}) { const { limit = 20, days = 3 } = args; // 自动检测邮箱类型并选择最佳协议 const email = process.env.EMAIL_USER || process.env.WECHAT_EMAIL_USER; const emailType = process.env.EMAIL_TYPE; if (email) { const provider = this.detectEmailProvider(email, emailType); if (provider && EMAIL_CONFIGS[provider]) { const config = EMAIL_CONFIGS[provider]; console.log(`使用${config.name}的${config.usePOP3 ? 'POP3' : 'IMAP'}协议获取邮件`); if (config.usePOP3) { return this.getRecentEmailsPOP3(args); } } } // 默认尝试IMAP,失败则尝试POP3 try { return await this.getRecentEmailsIMAP(args); } catch (error) { console.log('IMAP失败,尝试POP3:', error.message); return this.getRecentEmailsPOP3(args); } }
  • Input schema definition for the 'get_recent_emails' tool, specifying optional parameters for limit and days.
    inputSchema: { type: 'object', properties: { limit: { type: 'number', description: '返回邮件数量限制(默认20)' }, days: { type: 'number', description: '获取最近几天的邮件(默认3天)' } }, required: []
  • index.js:215-232 (registration)
    Tool registration in the ListTools response, including name, description, and input schema for 'get_recent_emails'.
    { name: 'get_recent_emails', description: '获取最近三天的邮件列表', inputSchema: { type: 'object', properties: { limit: { type: 'number', description: '返回邮件数量限制(默认20)' }, days: { type: 'number', description: '获取最近几天的邮件(默认3天)' } }, required: [] } },
  • Helper function implementing email fetching using IMAP protocol, including connection setup, searching recent emails, parsing headers, and filtering by date.
    async getRecentEmailsIMAP(args = {}) { const { limit = 20, days = 3 } = args; // 检查是否支持IMAP try { const imap = this.createIMAPConnection(); } catch (error) { return { content: [{ type: 'text', text: `❌ IMAP功能不可用: ${error.message}\n\n建议:\n1. 检查邮箱IMAP/POP3设置\n2. 确认使用正确的授权码\n3. 尝试使用QQ邮箱等其他邮箱服务` }] }; } return new Promise((resolve, reject) => { const imap = this.createIMAPConnection(); imap.once('ready', () => { imap.openBox('INBOX', true, (err, box) => { if (err) { imap.end(); return reject(err); } // 获取所有邮件,然后根据日期过滤 imap.search(['ALL'], (err, results) => { if (err) { imap.end(); return reject(err); } if (!results || results.length === 0) { imap.end(); return resolve({ content: [{ type: 'text', text: `最近${days}天内没有找到邮件。` }] }); } // 获取最近的邮件(取最后的一些邮件) const uids = results.slice(-Math.min(limit * 3, results.length)); // 获取邮件头部信息 const fetch = imap.fetch(uids, { bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)', struct: true }); const emails = []; fetch.on('message', (msg, seqno) => { let headers = {}; msg.on('body', (stream, info) => { let buffer = ''; stream.on('data', (chunk) => { buffer += chunk.toString('utf8'); }); stream.once('end', () => { headers = Imap.parseHeader(buffer); }); }); msg.once('attributes', (attrs) => { emails.push({ uid: attrs.uid, date: headers.date ? headers.date[0] : '', from: headers.from ? headers.from[0] : '', to: headers.to ? headers.to[0] : '', subject: headers.subject ? headers.subject[0] : '(无主题)' }); }); }); fetch.once('error', (err) => { imap.end(); reject(err); }); fetch.once('end', () => { imap.end(); // 计算日期范围 const since = new Date(); since.setDate(since.getDate() - days); // 过滤最近几天的邮件 const recentEmails = emails.filter(email => { const emailDate = new Date(email.date); return emailDate >= since; }); // 按日期排序(最新的在前) recentEmails.sort((a, b) => new Date(b.date) - new Date(a.date)); // 限制结果数量 const limitedEmails = recentEmails.slice(0, limit); if (limitedEmails.length === 0) { resolve({ content: [{ type: 'text', text: `最近${days}天内没有找到邮件。` }] }); return; } const emailList = limitedEmails.map(email => `📧 UID: ${email.uid}\n` + `📅 日期: ${email.date}\n` + `👤 发件人: ${email.from}\n` + `📝 主题: ${email.subject}\n` + `────────────────────────────────` ).join('\n'); resolve({ content: [{ type: 'text', text: `📬 最近${days}天的邮件列表 (共${limitedEmails.length}封):\n\n${emailList}` }] }); }); }); }); }); imap.once('error', (err) => { reject(err); }); imap.connect(); }); }
  • Helper function implementing email fetching using POP3 protocol, including connection, listing recent messages, retrieving, parsing with mailparser, and date filtering.
    async getRecentEmailsPOP3(args = {}) { const { limit = 20, days = 3 } = args; return new Promise((resolve, reject) => { const config = this.createPOP3Connection(); const pop3 = new POP3Client(config.port, config.hostname, { enabletls: config.tls, debug: false }); let emails = []; let messageCount = 0; pop3.on('connect', () => { pop3.login(config.username, config.password); }); pop3.on('login', (status, data) => { if (status) { pop3.list(); } else { reject(new Error('POP3登录失败: ' + data)); } }); pop3.on('list', (status, msgcount, msgnumber, data) => { if (status) { messageCount = msgcount; if (msgcount === 0) { pop3.quit(); resolve({ content: [{ type: 'text', text: '邮箱中没有邮件。' }] }); return; } // 获取最近的邮件(从最新的开始) const startMsg = Math.max(1, msgcount - limit + 1); const endMsg = msgcount; for (let i = endMsg; i >= startMsg; i--) { pop3.retr(i); } } else { reject(new Error('获取邮件列表失败: ' + data)); } }); pop3.on('retr', (status, msgnumber, data) => { if (status) { // 解析邮件 simpleParser(data, (err, parsed) => { if (!err) { // 检查邮件日期是否在指定范围内 const since = new Date(); since.setDate(since.getDate() - days); const emailDate = new Date(parsed.date); if (emailDate >= since) { emails.push({ uid: msgnumber, date: parsed.date ? parsed.date.toLocaleString() : '未知', from: parsed.from?.text || '未知', to: parsed.to?.text || '未知', subject: parsed.subject || '(无主题)' }); } } // 检查是否获取完所有邮件 if (emails.length > 0 || msgnumber === Math.max(1, messageCount - limit + 1)) { pop3.quit(); } }); } else { reject(new Error(`获取邮件${msgnumber}失败: ${data}`)); } }); pop3.on('quit', (status, data) => { // 按日期排序(最新的在前) emails.sort((a, b) => new Date(b.date) - new Date(a.date)); if (emails.length === 0) { resolve({ content: [{ type: 'text', text: `最近${days}天内没有找到邮件。` }] }); return; } const emailList = emails.map(email => `📧 邮件号: ${email.uid}\n` + `📅 日期: ${email.date}\n` + `👤 发件人: ${email.from}\n` + `📝 主题: ${email.subject}\n` + `────────────────────────────────` ).join('\n'); resolve({ content: [{ type: 'text', text: `📬 最近${days}天的邮件列表 (共${emails.length}封,POP3协议):\n\n${emailList}` }] }); }); pop3.on('error', (err) => { reject(new Error('POP3连接错误: ' + err.message)); }); }); }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/TimeCyber/email-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server