Skip to main content
Glama
TimeCyber

Email MCP Server

by TimeCyber

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));
        });
      });
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does (get recent emails) but lacks critical behavioral details such as whether this is a read-only operation, if it requires authentication, how it handles errors, or what the return format looks like (e.g., list structure, pagination). This is a significant gap for a tool with zero annotation coverage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence in Chinese that directly states the tool's purpose without any wasted words. It is appropriately sized and front-loaded, making it easy to understand at a glance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (a read operation with two parameters), no annotations, and no output schema, the description is incomplete. It adequately states the purpose but fails to provide necessary behavioral context (e.g., safety, authentication, return format) or usage guidelines, leaving gaps that could hinder an AI agent's ability to use the tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, with both parameters (limit and days) fully documented in the schema, including their types and default values. The description adds no additional parameter information beyond implying a three-day default for 'days', which is already covered in the schema. This meets the baseline score of 3 when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('获取' meaning 'get') and resource ('邮件列表' meaning 'email list'), and specifies a time scope ('最近三天' meaning 'last three days'). It distinguishes from siblings like get_email_content (which gets content of specific emails) and send_email (which sends emails). However, it doesn't explicitly contrast with list_supported_providers or other siblings, keeping it from a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for retrieving recent emails within a three-day window, but provides no explicit guidance on when to use this tool versus alternatives like get_email_content (for specific email details) or configure_email_server (for setup). No exclusions or prerequisites are mentioned, leaving usage context somewhat vague.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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