/** * 方案二:IMAP IDLE 实时监听新邮件 * * 通过 IMAP IDLE 命令保持长连接,实时监听收件箱中的新邮件到达。 * 适用于需要实时感知新邮件的场景,如:监听邮件后自动触发业务逻辑。 * * 依赖安装:npm install imapflow mailparser * 类型安装:npm install -D @types/mailparser * * 注意事项: * 1. IDLE 连接可能因网络问题断开,内置自动重连机制 * 2. 部分邮箱服务器对 IDLE 连接有超时限制(通常 29 分钟),imapflow 会自动处理 * 3. 生产环境建议配合进程管理工具(如 pm2)使用 */ /** 邮件连接配置 */ export interface ImapConfig { /** IMAP 服务器地址,例如 'imap.exmail.qq.com' */ host: string; /** IMAP 端口,默认 993(STARTTLS)或 993(隐式 TLS) */ port?: number; /** 是否使用隐式 TLS(端口 993),默认 false(使用 STARTTLS) */ secure?: boolean; /** 邮箱账号 */ user: string; /** 邮箱密码或应用专用密码/授权码 */ password: string; } /** 解析后的邮件结构 */ export interface EmailMessage { /** 邮件 UID */ uid: number; /** 邮件主题 */ subject: string; /** 发件人 */ from: string; /** 收件人 */ to: string; /** 邮件日期 */ date: Date | undefined; /** 纯文本内容 */ text: string | undefined; /** HTML 内容 */ html: string | false; /** Markdown 内容(由 HTML 或纯文本转换而来) */ markdown: string; /** 附件列表 */ attachments: Array<{ filename: string; contentType: string; size: number; }>; } /** 邮件监听配置 */ export interface WatchEmailsOptions extends ImapConfig { /** 邮箱文件夹,默认 'INBOX' */ mailbox?: string; /** 新邮件到达时的回调 */ onNewEmail: (email: EmailMessage) => void | Promise; /** 连接错误时的回调 */ onError?: (error: Error) => void; /** 连接成功时的回调 */ onConnected?: () => void; /** 断开连接时的回调 */ onDisconnected?: () => void; /** 断线后自动重连,默认 true */ autoReconnect?: boolean; /** 重连间隔(毫秒),默认 5000 */ reconnectInterval?: number; /** 最大重连次数,默认 Infinity */ maxReconnectAttempts?: number; /** 是否开启调试日志,默认 false */ debug?: boolean; } /** 邮件监听器实例,用于管理生命周期 */ export interface EmailWatcher { /** 停止监听并断开连接 */ stop: () => Promise; /** 当前是否已连接 */ isConnected: () => boolean; } /** * 启动邮件监听(基于 IMAP IDLE) * * @example * ```ts * const watcher = await watchEmails({ * host: 'imap.exmail.qq.com', * user: 'yourname@company.com', * password: 'your-app-password', * onNewEmail: (email) => { * console.log('📬 收到新邮件:', email.subject); * // 触发你的业务逻辑,比如推送到企微群 * }, * onError: (err) => { * console.error('监听出错:', err.message); * }, * }); * * // 需要停止时 * // await watcher.stop(); * ``` */ export declare function watchEmails(options: WatchEmailsOptions): Promise;