mcp-mail-server 1.1.5 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Server as e}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as t}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as r,CallToolRequestSchema as n}from"@modelcontextprotocol/sdk/types.js";import s from"imap";import{EventEmitter as o}from"events";import{simpleParser as i}from"mailparser";import a from"nodemailer";class IMAPClient extends o{imap=null;config;connected=!1;authenticated=!1;currentBox=null;constructor(e){super(),this.config=e}async connect(){return new Promise((e,t)=>{console.error(`[IMAP] Connecting to ${this.config.host}:${this.config.port} (TLS: ${this.config.tls})`);const r={user:this.config.username,password:this.config.password,host:this.config.host,port:this.config.port,tls:this.config.tls||!1,connTimeout:this.config.connTimeout||1e4,authTimeout:this.config.authTimeout||5e3,keepalive:!1!==this.config.keepalive};this.imap=new s(r),this.imap.once("ready",async()=>{console.error("[IMAP] Connection ready"),this.connected=!0,this.authenticated=!0;try{await this.openBox("INBOX",!0),console.error("[IMAP] Auto-opened INBOX")}catch(e){console.error("[IMAP] Failed to auto-open INBOX:",e instanceof Error?e.message:String(e))}e()}),this.imap.once("error",e=>{console.error("[IMAP] Connection error:",e.message),t(new Error(`IMAP connection failed: ${e.message}`))}),this.imap.once("end",()=>{console.error("[IMAP] Connection ended"),this.connected=!1,this.authenticated=!1,this.currentBox=null}),this.imap.connect()})}async openBox(e="INBOX",t=!1){if(!this.imap||!this.authenticated)throw new Error("Not connected or authenticated");return new Promise((r,n)=>{this.imap.openBox(e,t,(t,s)=>{if(t)return console.error(`[IMAP] Failed to open box ${e}:`,t.message),void n(new Error(`Failed to open mailbox: ${t.message}`));console.error(`[IMAP] Opened box ${e}`),this.currentBox=e;const o={name:e,messages:{total:s.messages.total,new:s.messages.new,unseen:s.messages.unseen},permFlags:s.permFlags,uidvalidity:s.uidvalidity,uidnext:s.uidnext};r(o)})})}async getBoxes(){if(!this.imap||!this.authenticated)throw new Error("Not connected or authenticated");return new Promise((e,t)=>{this.imap.getBoxes((r,n)=>{r?t(new Error(`Failed to get boxes: ${r.message}`)):e(n)})})}async search(e=["ALL"]){if(!this.imap)throw new Error("Not connected to IMAP server");return this.currentBox||await this.openBox("INBOX",!0),new Promise((t,r)=>{this.imap.search([e],(e,n)=>{if(e)return console.error("[IMAP] Search failed:",e.message),void r(new Error(`Search failed: ${e.message}`));console.error(`[IMAP] Search found ${n.length} messages`),t(n)})})}async fetchMessages(e,t={}){if(!this.imap)throw new Error("Not connected to IMAP server");this.currentBox||await this.openBox("INBOX",!0);const r={bodies:t.bodies||["HEADER","TEXT"],struct:!1!==t.struct,envelope:!1!==t.envelope,markSeen:t.markSeen||!1,...t};return new Promise((t,n)=>{const s=[],o=new Map;if(0===e.length)return void t(s);const a=this.imap.fetch(e,r);a.on("message",(e,t)=>{console.error(`[IMAP] Processing message ${t}`);let r={},n="";const s=[],i={uid:0,id:t,flags:[],date:"",size:0};e.on("body",(e,t)=>{const o=[];e.on("data",e=>{o.push(e),s.push(e)}),e.once("end",()=>{const e=Buffer.concat(o);if("HEADER"===t.which){const t=e.toString("utf8");r=this.parseHeaders(t)}else"TEXT"===t.which&&(n=e.toString("utf8"))})}),e.once("attributes",e=>{i.uid=e.uid,i.flags=e.flags||[];const t=e.date||new Date;i.date=t.toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),i.size=e.size||0}),e.once("end",()=>{console.error(`[IMAP] Message ${t} processed, preparing for parse`),o.set(t,{message:i,headers:r,body:n,rawBuffer:Buffer.concat(s)})})}),a.once("error",e=>{console.error("[IMAP] Fetch error:",e.message),n(new Error(`Fetch failed: ${e.message}`))}),a.once("end",async()=>{console.error(`[IMAP] Fetch completed, parsing ${o.size} messages`);for(const[e,t]of o)try{const e=await i(t.rawBuffer),r=e=>e?Array.isArray(e)?e.map(e=>n(e)).filter(Boolean).join(", "):n(e):"",n=e=>{if(!e)return"";if("string"==typeof e){const t=e.match(/<([^>]+)>/)||e.match(/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:e}if(e&&"object"==typeof e){if(e.address)return e.address;if(e.text){const t=e.text.match(/<([^>]+)>/)||e.text.match(/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:e.text}}return""};s.push({...t.message,subject:e.subject||"No Subject",from:r(e.from),to:r(e.to),cc:r(e.cc)||void 0,bcc:r(e.bcc)||void 0,text:e.text,html:e.html})}catch(r){console.error(`[IMAP] Failed to parse message ${e}:`,r),s.push({...t.message,subject:t.headers.subject||"Parse Failed",from:t.headers.from||"",to:t.headers.to||"",cc:t.headers.cc||void 0,bcc:t.headers.bcc||void 0,text:t.body.trim()})}console.error(`[IMAP] All messages parsed, returning ${s.length} messages`),t(s)})})}async getMessage(e){const t=await this.fetchMessages([e]);if(0===t.length)throw new Error(`Message with UID ${e} not found`);return t[0]}async deleteMessage(e){if(!this.imap)throw new Error("Not connected to IMAP server");return this.currentBox||await this.openBox("INBOX",!1),new Promise((t,r)=>{this.imap.addFlags(e,["\\Deleted"],n=>{if(n)return console.error(`[IMAP] Failed to mark message ${e} as deleted:`,n.message),void r(new Error(`Failed to delete message: ${n.message}`));console.error(`[IMAP] Message ${e} marked for deletion`),this.imap.expunge(n=>{if(n)return console.error("[IMAP] Failed to expunge:",n.message),void r(new Error(`Failed to expunge deleted messages: ${n.message}`));console.error(`[IMAP] Message ${e} deleted successfully`),t()})})})}async getMessageCount(){return this.currentBox||await this.openBox("INBOX",!0),(await this.search(["ALL"])).length}async getUnseenMessages(){const e=await this.search(["UNSEEN"]);return this.fetchMessages(e)}async getRecentMessages(){const e=await this.search(["RECENT"]);return this.fetchMessages(e)}parseHeaders(e){const t={},r=e.split("\r\n");let n="",s="";for(const e of r)if(e.match(/^\s/)&&n)s+=" "+e.trim();else{n&&(t[n.toLowerCase()]=s.trim());const r=e.indexOf(":");r>-1?(n=e.substring(0,r).trim(),s=e.substring(r+1).trim()):(n="",s="")}return n&&(t[n.toLowerCase()]=s.trim()),t}async disconnect(){if(this.imap)return this.connected?new Promise(e=>{const t=setTimeout(()=>{console.error("[IMAP] Disconnect timeout, forcing cleanup"),this.connected=!1,this.authenticated=!1,this.currentBox=null,this.imap=null,e()},5e3);this.imap.once("end",()=>{clearTimeout(t),console.error("[IMAP] Disconnected"),this.connected=!1,this.authenticated=!1,this.currentBox=null,this.imap=null,e()}),this.imap.once("error",r=>{clearTimeout(t),console.error("[IMAP] Disconnect error:",r.message),this.connected=!1,this.authenticated=!1,this.currentBox=null,this.imap=null,e()});try{this.imap.end()}catch(r){clearTimeout(t),console.error("[IMAP] Error calling end():",r),this.connected=!1,this.authenticated=!1,this.currentBox=null,this.imap=null,e()}}):(this.imap=null,this.authenticated=!1,void(this.currentBox=null))}isConnected(){return this.connected&&this.authenticated}getCurrentBox(){return this.currentBox}getCurrentUsername(){return this.config?.username||null}async saveMessageToFolder(e,t="INBOX.Sent"){if(!this.connected)throw new Error("IMAP client is not connected");return new Promise((r,n)=>{this.imap.openBox(t,!1,s=>{s?(console.warn(`[IMAP] Folder ${t} not found, trying to create it`),this.imap.addBox(t,s=>{if(s)return console.error(`[IMAP] Failed to create folder ${t}:`,s.message),void this.trySaveToAlternateSentFolders(e,r,n);this.saveToOpenedFolder(e,t,r,n)})):this.saveToOpenedFolder(e,t,r,n)})})}saveToOpenedFolder(e,t,r,n){this.imap.append(e,{mailbox:t},e=>{e?(console.error(`[IMAP] Failed to save message to ${t}:`,e.message),n(new Error(`Failed to save message to ${t}: ${e.message}`))):r()})}trySaveToAlternateSentFolders(e,t,r){const n=["Sent","SENT","Sent Items","Sent Messages","已发送"];let s=0;const o=()=>{if(s>=n.length)return console.warn("[IMAP] All sent folder attempts failed, message not saved to sent folder"),void t();const i=n[s++];this.imap.openBox(i,!1,n=>{n?o():this.saveToOpenedFolder(e,i,t,r)})};o()}}class SMTPClient{transporter=null;config;constructor(e){this.config=e}async connect(){this.transporter=a.createTransport({host:this.config.host,port:this.config.port,secure:this.config.secure||!1,auth:{user:this.config.username,pass:this.config.password}});try{this.transporter&&await this.transporter.verify()}catch(e){throw new Error(`SMTP connection failed: ${e instanceof Error?e.message:String(e)}`)}}async sendMail(e){if(!this.transporter)throw new Error("SMTP client not connected");const t={from:e.from||this.config.username,to:Array.isArray(e.to)?e.to.join(", "):e.to,cc:e.cc?Array.isArray(e.cc)?e.cc.join(", "):e.cc:void 0,bcc:e.bcc?Array.isArray(e.bcc)?e.bcc.join(", "):e.bcc:void 0,subject:e.subject,text:e.text,html:e.html,attachments:e.attachments};try{const e=await this.transporter.sendMail(t);return{messageId:e.messageId,response:e.response,accepted:e.accepted||[],rejected:e.rejected||[]}}catch(e){throw new Error(`Failed to send email: ${e instanceof Error?e.message:String(e)}`)}}getCurrentUsername(){return this.config?.username||null}isConnected(){return null!==this.transporter}async disconnect(){if(this.transporter)try{this.transporter.close(),console.error("[SMTP] Disconnected successfully")}catch(e){console.error("[SMTP] Error during disconnect:",e instanceof Error?e.message:String(e))}finally{this.transporter=null}}}function c(e,t){const r=process.env[e];if(!r)throw new Error(`Missing required environment variable: ${e}. Please set this variable in your MCP server configuration.`);return r}function l(e){const t=process.env[e];if(!t)throw new Error(`Missing required environment variable: ${e}. Please set this variable to 'true' or 'false' in your MCP server configuration.`);if("true"!==t.toLowerCase()&&"false"!==t.toLowerCase())throw new Error(`Invalid boolean value for environment variable ${e}: ${t}. Must be 'true' or 'false'.`);return"true"===t.toLowerCase()}function d(e){const t=process.env[e];if(!t)throw new Error(`Missing required environment variable: ${e}. Please set this variable to a valid number in your MCP server configuration.`);const r=parseInt(t,10);if(isNaN(r))throw new Error(`Invalid number value for environment variable ${e}: ${t}. Must be a valid number.`);return r}const h={IMAP:{host:c("IMAP_HOST"),port:d("IMAP_PORT"),username:c("EMAIL_USER"),password:c("EMAIL_PASS"),tls:l("IMAP_SECURE")},SMTP:{host:c("SMTP_HOST"),port:d("SMTP_PORT"),username:c("EMAIL_USER"),password:c("EMAIL_PASS"),secure:l("SMTP_SECURE")}},m=["INBOX.Sent","Sent","SENT","Sent Items","Sent Messages","已发送"],u=["INBOX",...m];(new class{server;imapClient=null;smtpClient=null;isInitializing=!1;formatError(e,t){return`${t}: ${e instanceof Error?e.message:String(e)}`}isDateOnly(e){return[/^\d{4}-\d{2}-\d{2}$/,/^\d{2}-\w{3}-\d{4}$/,/^\w{3}\s+\d{1,2},?\s+\d{4}$/].some(t=>t.test(e.trim()))}filterMessagesByDateRange(e,t,r){if(!t&&!r)return e;let n=null,s=null;t&&(n=new Date(t),isNaN(n.getTime())?(console.error(`[Filter] Invalid start date format: ${t}, skipping start date filter`),n=null):console.error(`[Filter] Start date parsed as: ${n.toISOString()}`)),r&&(s=new Date(r),isNaN(s.getTime())?(console.error(`[Filter] Invalid end date format: ${r}, skipping end date filter`),s=null):this.isDateOnly(r)?(s.setHours(23,59,59,999),console.error(`[Filter] End date adjusted to end of day: ${s.toISOString()}`)):console.error(`[Filter] End date parsed as: ${s.toISOString()}`));const o=e.length,i=e.filter(e=>{if(!e.date)return!0;const t=new Date(e.date);return!(!isNaN(t.getTime())&&(n&&t<n||s&&t>s))});return console.error(`[Filter] Date filtering: ${o} -> ${i.length} messages`),i}async searchInMultipleMailboxes(e,t,r,n="",s=""){const o=["INBOX"];let i=!1;for(const e of m)try{await this.imapClient.openBox(e,!0),o.push(e),i=!0;break}catch(t){console.error(`[IMAP] Failed to open sent mailbox ${e}: ${t instanceof Error?t.message:String(t)}`)}const a={searchType:t,searchValue:r,searchCriteria:e,mailboxesSearched:[],totalMatches:0,messages:[]};for(const t of o)try{console.error(`[IMAP] Searching in mailbox: ${t}`),await this.imapClient.openBox(t,!0);const r=await this.imapClient.search(e);console.error(`[IMAP] Found ${r.length} messages in ${t}`);let o=[],i=[];if(r.length>0){console.error(`[IMAP] Auto-fetching content for ${r.length} messages from ${t}`);let e=(await this.imapClient.fetchMessages(r)).map(e=>({...e,sourceMailbox:t}));(n||s)&&(e=this.filterMessagesByDateRange(e,n,s)),o=e,i=e.map(e=>e.uid),a.messages.push(...o)}const c={mailbox:t,matchingUIDs:i,messageCount:o.length};a.mailboxesSearched.push(c)}catch(e){console.error(`[IMAP] Error searching in ${t}:`,e),a.mailboxesSearched.push({mailbox:t,error:`Failed to search: ${e instanceof Error?e.message:String(e)}`,matchingUIDs:[],messageCount:0})}if(a.totalMatches=a.messages.length,a.messages.sort((e,t)=>{const r=new Date(e.date||0);return new Date(t.date||0).getTime()-r.getTime()}),a.totalMatches>0){let e=`Found and retrieved ${a.totalMatches} messages across ${a.mailboxesSearched.length} mailboxes`;(n||s)&&(e+=" (filtered by date range)"),a.note=e}else a.note="No messages found in any of the searched mailboxes";return i||(a.warning="Could not find sent mailbox - only searched INBOX"),a}constructor(){this.validateConfig(),this.server=new e({name:"mcp-mail",version:"1.0.0"},{capabilities:{tools:{}}}),this.setupToolHandlers(),this.setupErrorHandling()}setupErrorHandling(){this.server.onerror=e=>console.error("[MCP Error]",e),process.on("SIGINT",async()=>{this.imapClient&&await this.imapClient.disconnect(),this.smtpClient&&await this.smtpClient.disconnect(),await this.server.close(),process.exit(0)})}setupToolHandlers(){this.server.setRequestHandler(r,async()=>({tools:[{name:"connect_all",description:"Connect to both IMAP and SMTP servers simultaneously",inputSchema:{type:"object",properties:{}}},{name:"list_mailboxes",description:"List all available mailboxes (folders). Auto-connects if not already connected.",inputSchema:{type:"object",properties:{}}},{name:"open_mailbox",description:"Open a specific mailbox (folder) and optionally retrieve sent mailbox info. Due to IMAP protocol limitations, only one mailbox stays open. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{mailboxName:{type:"string",description:"Name of the mailbox to open (default: INBOX)",default:"INBOX"},readOnly:{type:"boolean",description:"Open mailbox in read-only mode (default: false)",default:!1},openSent:{type:"boolean",description:"Also retrieve sent mailbox information (default: true)",default:!0}}}},{name:"get_message_count",description:"Get the total number of messages in current mailbox. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{}}},{name:"get_unseen_messages",description:"Get all unseen (unread) messages. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{}}},{name:"get_recent_messages",description:"Get all recent messages. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{}}},{name:"search_by_sender",description:"Search messages from a specific sender with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{sender:{type:"string",description:"Email address of the sender to search for"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["sender"]}},{name:"search_by_subject",description:"Search messages by subject keywords with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{subject:{type:"string",description:"Keywords to search in email subject"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["subject"]}},{name:"search_by_recipient",description:"Search messages sent to a specific recipient email address with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{recipient:{type:"string",description:"Email address of the recipient to search for"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["recipient"]}},{name:"search_since_date",description:"Search messages from a specific date until now (not for date ranges). Use search_messages for complex date ranges.",inputSchema:{type:"object",properties:{date:{type:"string",description:'Start date to search from (searches from this date to present). Formats: "April 20, 2010", "20-Apr-2010", or "2010-04-20"'}},required:["date"]}},{name:"search_unread_from_sender",description:"Search unread messages from a specific sender with optional date range (demonstrates AND logic). Auto-connects if not already connected.",inputSchema:{type:"object",properties:{sender:{type:"string",description:"Email address of the sender"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["sender"]}},{name:"search_by_body",description:"Search messages containing specific text in the body with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{text:{type:"string",description:"Text to search for in message body"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["text"]}},{name:"search_with_keyword",description:"Search messages with specific keyword/flag with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{keyword:{type:"string",description:"Keyword to search for"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["keyword"]}},{name:"get_messages",description:"Retrieve multiple messages by their UIDs. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{uids:{type:"array",description:"Array of message UIDs to retrieve",items:{type:"number"}},markSeen:{type:"boolean",description:"Mark messages as seen when retrieving (default: false)",default:!1}},required:["uids"]}},{name:"get_message",description:"Retrieve a specific email message by UID. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{uid:{type:"number",description:"Message UID to retrieve"},markSeen:{type:"boolean",description:"Mark message as seen when retrieving (default: false)",default:!1}},required:["uid"]}},{name:"send_email",description:"Send an email via SMTP. Auto-connects to SMTP server if not already connected.",inputSchema:{type:"object",properties:{to:{type:"string",description:"Recipient email address(es), comma-separated"},subject:{type:"string",description:"Email subject"},text:{type:"string",description:"Plain text email body"},html:{type:"string",description:"HTML email body (optional)"},cc:{type:"string",description:"CC recipients, comma-separated (optional)"},bcc:{type:"string",description:"BCC recipients, comma-separated (optional)"}},required:["to","subject"]}},{name:"reply_to_email",description:"Reply to a specific email by UID. Automatically sets reply headers, adds Re: prefix, and includes original message. Auto-connects to both IMAP and SMTP if not already connected.",inputSchema:{type:"object",properties:{originalUid:{type:"number",description:"UID of the original message to reply to"},text:{type:"string",description:"Reply message text"},html:{type:"string",description:"Reply message HTML (optional)"},replyToAll:{type:"boolean",description:"Reply to all recipients instead of just sender (default: false)",default:!1},includeOriginal:{type:"boolean",description:"Include original message in reply (default: true)",default:!0}},required:["originalUid"]}},{name:"delete_message",description:"Delete a specific email message by UID. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{uid:{type:"number",description:"Message UID to delete"}},required:["uid"]}},{name:"get_connection_status",description:"Check the current connection status of both IMAP and SMTP servers.",inputSchema:{type:"object",properties:{}}},{name:"disconnect_all",description:"Disconnect from both IMAP and SMTP servers. Only disconnects if currently connected.",inputSchema:{type:"object",properties:{}}}]})),this.server.setRequestHandler(n,async e=>{const{name:t,arguments:r}=e.params;try{switch(t){case"open_mailbox":return await this.handleOpenMailbox(r||{});case"list_mailboxes":return await this.handleListMailboxes();case"search_by_sender":return await this.handleSearchBySender(r||{});case"search_by_subject":return await this.handleSearchBySubject(r);case"search_by_recipient":return await this.handleSearchByRecipient(r);case"search_since_date":return await this.handleSearchSinceDate(r);case"search_unread_from_sender":return await this.handleSearchUnreadFromSender(r);case"search_by_body":return await this.handleSearchByBody(r);case"search_with_keyword":return await this.handleSearchWithKeyword(r);case"get_messages":return await this.handleGetMessages(r);case"get_message":return await this.handleGetMessage(r);case"delete_message":return await this.handleDeleteMessage(r);case"get_message_count":return await this.handleGetMessageCount();case"get_unseen_messages":return await this.handleGetUnseenMessages();case"get_recent_messages":return await this.handleGetRecentMessages();case"get_connection_status":return await this.handleGetConnectionStatus();case"send_email":return await this.handleSendEmail(r);case"reply_to_email":return await this.handleReplyToEmail(r);case"connect_all":return await this.handleConnectAll();case"disconnect_all":return await this.handleDisconnectAll();default:throw new Error(`Unknown tool: ${t}`)}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:String(e)}`}]}}})}async ensureIMAPConnection(){if(!this.imapClient||!this.imapClient.isConnected())if(this.isInitializing)for(;this.isInitializing;)await new Promise(e=>setTimeout(e,100));else{this.isInitializing=!0;try{const e=h.IMAP;console.error(`[IMAP] Auto-connecting to ${e.host}:${e.port}`),this.imapClient=new IMAPClient(e),await this.imapClient.connect(),console.error("[IMAP] Auto-connection successful")}finally{this.isInitializing=!1}}}async ensureSMTPConnection(){if(this.smtpClient)return;const e=h.SMTP;console.error(`[SMTP] Auto-connecting to ${e.host}:${e.port}`),this.smtpClient=new SMTPClient(e),await this.smtpClient.connect(),console.error("[SMTP] Auto-connection successful")}async ensureRequiredConnections(e=!1,t=!1){e&&await this.ensureIMAPConnection(),t&&await this.ensureSMTPConnection()}async handleOpenMailbox(e){await this.ensureRequiredConnections(!0,!1);const t=e.mailboxName||"INBOX",r=e.readOnly||!1,n=!1!==e.openSent;try{const e={},s=await this.imapClient.openBox(t,r);if(e[t]=s,e.currentlyOpen=t,n&&"INBOX.Sent"!==t&&"Sent"!==t&&"SENT"!==t)try{const n=["INBOX.Sent","Sent","SENT","Sent Items","Sent Messages","已发送"];let s=!1;for(const o of n)try{const n=await this.imapClient.openBox(o,!0);e[o]=n,s=!0,await this.imapClient.openBox(t,r),e.currentlyOpen=t,e.note=`Retrieved info from both ${t} and ${o}. Currently open: ${t}`;break}catch(e){console.error(`[IMAP] Failed to open sent mailbox ${o}: ${e instanceof Error?e.message:String(e)}`)}s||(e.sentBoxWarning="Could not find any sent mailbox")}catch(t){e.sentBoxError=`Failed to access sent mailbox: ${t instanceof Error?t.message:String(t)}`}return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to open mailbox"))}}async handleListMailboxes(){await this.ensureRequiredConnections(!0,!1);try{const e=await this.imapClient.getBoxes(),t=(e,r="",n=new Set)=>{if(n.has(e))return{name:r,circular:!0};n.add(e);const s={name:r,attribs:e.attribs||[],delimiter:e.delimiter||".",selectable:!e.attribs?.includes("\\Noselect")};if(e.children&&Object.keys(e.children).length>0){s.children={};for(const[o,i]of Object.entries(e.children)){const a=r?`${r}${e.delimiter||"."}${o}`:o;s.children[o]=t(i,a,new Set(n))}}return n.delete(e),s},r={};for(const[n,s]of Object.entries(e))r[n]=t(s,n);return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to list mailboxes"))}}async handleSearchBySender(e){await this.ensureRequiredConnections(!0,!1);const t=e.sender,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("sender parameter is required");try{const e=["FROM",t];console.error("[IMAP] Searching messages from sender across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"By Sender",t,r,n);return s.sender=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search by sender failed"))}}async handleSearchBySubject(e){await this.ensureRequiredConnections(!0,!1);const t=e.subject,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("subject parameter is required");try{const e=["SUBJECT",t];console.error("[IMAP] Searching messages with subject across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"By Subject",t,r,n);return s.subjectKeywords=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search by subject failed"))}}async handleSearchByRecipient(e){await this.ensureRequiredConnections(!0,!1);const t=e.recipient,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("recipient parameter is required");try{const e=["TO",t];console.error("[IMAP] Searching messages to recipient across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"By Recipient",t,r,n);return s.recipient=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search by recipient failed"))}}async handleSearchSinceDate(e){await this.ensureRequiredConnections(!0,!1);const t=e.date;if(!t)throw new Error("date parameter is required");try{const e=["SINCE",t];console.error("[IMAP] Searching messages since date across all mailboxes:",t);const r=await this.searchInMultipleMailboxes(e,"Since Date",t);return r.sinceDate=t,r.note='Date format should be like "April 20, 2010" or "20-Apr-2010". Searched across multiple mailboxes.',{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search since date failed"))}}async handleSearchUnreadFromSender(e){await this.ensureRequiredConnections(!0,!1);const t=e.sender,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("sender parameter is required");try{const e=["UNSEEN",["FROM",t]];console.error("[IMAP] Searching unread messages from sender across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"Unread messages from specific sender",t,r,n);return s.sender=t,r&&(s.startDate=r),n&&(s.endDate=n),s.note="By default, all criteria are ANDed together - finds messages that are BOTH unread AND from the specified sender. Searched across multiple mailboxes.",{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search unread from sender failed"))}}async handleSearchByBody(e){await this.ensureRequiredConnections(!0,!1);const t=e.text,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("text parameter is required");try{const e=["BODY",t];console.error("[IMAP] Searching messages with body text across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"By Body Text",t,r,n);return s.bodyText=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search by body failed"))}}async handleSearchWithKeyword(e){await this.ensureRequiredConnections(!0,!1);const t=e.keyword,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("keyword parameter is required");try{const e=["KEYWORD",t];console.error("[IMAP] Searching messages with keyword across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"With Keyword",t,r,n);return s.keyword=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search with keyword failed"))}}async handleGetMessages(e){await this.ensureRequiredConnections(!0,!1);const t=e.uids;if(!Array.isArray(t))throw new Error("uids must be an array of numbers");const r=e.markSeen||!1;try{const e=await this.imapClient.fetchMessages(t,{markSeen:r});return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to get messages"))}}async handleGetMessage(e){await this.ensureRequiredConnections(!0,!1);const t=e.uid;if("number"!=typeof t)throw new Error("uid must be a number");try{const e=await this.imapClient.getMessage(t);return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to get message"))}}async handleDeleteMessage(e){await this.ensureRequiredConnections(!0,!1);const t=e.uid;if("number"!=typeof t)throw new Error("uid must be a number");try{return await this.imapClient.deleteMessage(t),{content:[{type:"text",text:`Message with UID ${t} deleted successfully`}]}}catch(e){throw new Error(this.formatError(e,"Failed to delete message"))}}async handleGetMessageCount(){await this.ensureRequiredConnections(!0,!1);try{return{content:[{type:"text",text:`Total messages: ${await this.imapClient.getMessageCount()}`}]}}catch(e){throw new Error(this.formatError(e,"Failed to get message count"))}}async handleGetUnseenMessages(){await this.ensureRequiredConnections(!0,!1);try{const e=await this.imapClient.getUnseenMessages();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to get unseen messages"))}}async handleGetRecentMessages(){await this.ensureRequiredConnections(!0,!1);try{const e=await this.imapClient.getRecentMessages();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to get recent messages"))}}async handleGetConnectionStatus(){const e={timestamp:(new Date).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),connections:{imap:{connected:!1,currentBox:null,serverInfo:`${h.IMAP.host}:${h.IMAP.port}`,username:h.IMAP.username,tls:h.IMAP.tls,status:"Not connected"},smtp:{connected:!1,serverInfo:`${h.SMTP.host}:${h.SMTP.port}`,username:h.SMTP.username,secure:h.SMTP.secure,status:"Not connected"}}};return this.imapClient&&(e.connections.imap.connected=this.imapClient.isConnected(),e.connections.imap.currentBox=this.imapClient.getCurrentBox(),e.connections.imap.connected?e.connections.imap.status=e.connections.imap.currentBox?`Connected - Current mailbox: ${e.connections.imap.currentBox}`:"Connected - No mailbox open":e.connections.imap.status="Connection lost or failed"),this.smtpClient&&(e.connections.smtp.connected=!0,e.connections.smtp.status="Connected and ready"),{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}async handleSendEmail(e){await this.ensureRequiredConnections(!1,!0);const t={to:e.to.split(",").map(e=>e.trim()),subject:e.subject,text:e.text,html:e.html,cc:e.cc?e.cc.split(",").map(e=>e.trim()):void 0,bcc:e.bcc?e.bcc.split(",").map(e=>e.trim()):void 0};if(!t.text&&!t.html)throw new Error("Either text or html content is required");try{const e=await this.smtpClient.sendMail(t);await this.saveSentMessage(t,e.messageId);const r={...e,sentFolderSaved:!0,note:"Email sent successfully and saved to sent folder"};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to send email"))}}async handleReplyToEmail(e){await this.ensureRequiredConnections(!0,!0);const t=e.originalUid,r=e.text,n=e.html,s=e.replyToAll||!1,o=!1!==e.includeOriginal;if("number"!=typeof t)throw new Error("originalUid must be a number");if(!r)throw new Error("text parameter is required");try{await this.ensureMailboxOpen(),console.error(`[Reply] Fetching original message with UID: ${t}`);const e=await this.findMessageInMultipleMailboxes(t);if(!e)throw new Error(`Original message with UID ${t} not found in any mailbox`);const i=this.extractEmailFromAddress(e.from);if(!i)throw new Error("Could not extract sender email from original message");let a=[i],c=[];if(s){const t=this.extractEmailsFromAddressField(e.to),r=this.extractEmailsFromAddressField(e.cc),n=[...t,...r].filter(e=>e!==h.IMAP.username&&e!==i);n.length>0&&(c=n)}let l=e.subject||"";l.toLowerCase().startsWith("re:")||(l=`Re: ${l}`);let d=r,m=n;if(o&&e){const t=e.date?new Date(e.date).toLocaleString():"Unknown Date",s=e.from||"Unknown Sender";if(d=`${r}\n\n${this.buildQuotedText(e.text||"",t,s)}`,n||e.html){const o=this.buildQuotedHtml(e.html||e.text||"",t,s);m=`${n||this.textToHtml(r)}<br><br>${o}`}}const u={to:a,cc:c.length>0?c:void 0,subject:l,text:d,html:m};console.error(`[Reply] Sending reply to: ${a.join(", ")}${c.length>0?` (CC: ${c.join(", ")})`:""}`);const p=await this.smtpClient.sendMail(u);await this.saveSentMessage(u,p.messageId);const g={originalUid:t,originalFrom:i,originalSubject:e.subject,replyToAll:s,includeOriginal:o,recipients:{to:a,cc:c.length>0?c:void 0}},f={...p,replyInfo:g,sentFolderSaved:!0,note:"Reply sent successfully and saved to sent folder"};return{content:[{type:"text",text:JSON.stringify(f,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to reply to email"))}}extractEmailFromAddress(e){if(!e)return null;if(Array.isArray(e)&&e.length>0)return e[0].address||e[0];if("string"==typeof e){const t=e.match(/<([^>]+)>/)||e.match(/([^\s<>]+@[^\s<>]+)/);return t?t[1]:e}return e.address||null}extractEmailsFromAddressField(e){if(!e)return[];if(Array.isArray(e))return e.map(e=>e.address||e).filter(Boolean);if("string"==typeof e)return e.split(",").map(e=>{const t=e.trim().match(/<([^>]+)>/)||e.trim().match(/([^\s<>]+@[^\s<>]+)/);return t?t[1]:e.trim()}).filter(Boolean);const t=this.extractEmailFromAddress(e);return t?[t]:[]}buildQuotedText(e,t,r){return`On ${t}, ${r} wrote:\n${e.split("\n").map(e=>`> ${e}`).join("\n")}`}buildQuotedHtml(e,t,r){return`<div style="border-left: 3px solid #ccc; padding-left: 10px; margin-left: 10px; color: #666;">\n <p><strong>On ${t}, ${r} wrote:</strong></p>\n <div>${e.replace(/\n/g,"<br>")}</div>\n </div>`}textToHtml(e){return e.replace(/\n/g,"<br>").replace(/ /g,"&nbsp;&nbsp;")}async findMessageInMultipleMailboxes(e){if(this.imapClient.getCurrentBox())try{return await this.imapClient.getMessage(e)}catch(e){console.error(`[Search] Message not found in current mailbox: ${e instanceof Error?e.message:String(e)}`)}for(const t of u)try{await this.imapClient.openBox(t,!0);const r=await this.imapClient.getMessage(e);return console.error(`[Search] Found message in mailbox: ${t}`),r}catch(e){console.error(`[Search] Message not found in ${t}: ${e instanceof Error?e.message:String(e)}`)}return null}async ensureMailboxOpen(e="INBOX"){this.imapClient.getCurrentBox()||(console.error(`[IMAP] No mailbox currently open, opening ${e}`),await this.imapClient.openBox(e,!0))}async handleConnectAll(){const e=[];try{if(this.imapClient&&this.imapClient.isConnected()){const t=this.imapClient.getCurrentUsername(),r=h.IMAP.username;t!==r?(console.error(`[IMAP] User mismatch: current=${t}, config=${r}, reconnecting...`),await this.imapClient.disconnect(),await this.ensureIMAPConnection(),e.push("✅ IMAP: Reconnected with correct user")):e.push("ℹ️ IMAP: Already connected")}else await this.ensureIMAPConnection(),e.push("✅ IMAP: Connected successfully")}catch(t){e.push(`❌ IMAP: Connection failed - ${t instanceof Error?t.message:String(t)}`)}try{if(this.smtpClient&&this.smtpClient.isConnected()){const t=this.smtpClient.getCurrentUsername(),r=h.SMTP.username;t!==r?(console.error(`[SMTP] User mismatch: current=${t}, config=${r}, reconnecting...`),await this.smtpClient.disconnect(),await this.ensureSMTPConnection(),e.push("✅ SMTP: Reconnected with correct user")):e.push("ℹ️ SMTP: Already connected")}else await this.ensureSMTPConnection(),e.push("✅ SMTP: Connected successfully")}catch(t){e.push(`❌ SMTP: Connection failed - ${t instanceof Error?t.message:String(t)}`)}return{content:[{type:"text",text:e.join("\n")}]}}async handleDisconnectAll(){const e=[];if(this.imapClient)try{await this.imapClient.disconnect(),this.imapClient=null,e.push("✅ IMAP: Disconnected successfully")}catch(t){e.push(`❌ IMAP: Disconnect failed - ${t instanceof Error?t.message:String(t)}`)}else e.push("ℹ️ IMAP: Not connected");if(this.smtpClient)try{await this.smtpClient.disconnect(),this.smtpClient=null,e.push("✅ SMTP: Disconnected successfully")}catch(t){e.push(`❌ SMTP: Disconnect failed - ${t instanceof Error?t.message:String(t)}`)}else e.push("ℹ️ SMTP: Not connected");return{content:[{type:"text",text:e.join("\n")}]}}validateConfig(){try{console.error("=== MCP Mail Server Configuration ==="),console.error(`IMAP: ${h.IMAP.host}:${h.IMAP.port} (TLS: ${h.IMAP.tls})`),console.error(`SMTP: ${h.SMTP.host}:${h.SMTP.port} (Secure: ${h.SMTP.secure})`),console.error(`User: ${h.IMAP.username}`),console.error("Password: [CONFIGURED]"),console.error("Configuration loaded successfully")}catch(e){throw console.error("Configuration error:",e instanceof Error?e.message:String(e)),console.error("Please ensure all required environment variables are set in your MCP server configuration."),e}}buildRawEmailMessage(e,t){const r=(new Date).toUTCString();let n="";if(n+=`Message-ID: ${t||`<${Date.now()}.${Math.random().toString(36)}@${h.IMAP.host}>`}\r\n`,n+=`Date: ${r}\r\n`,n+=`From: ${h.IMAP.username}\r\n`,n+=`To: ${Array.isArray(e.to)?e.to.join(", "):e.to}\r\n`,e.cc&&(n+=`Cc: ${Array.isArray(e.cc)?e.cc.join(", "):e.cc}\r\n`),e.bcc&&(n+=`Bcc: ${Array.isArray(e.bcc)?e.bcc.join(", "):e.bcc}\r\n`),n+=`Subject: ${e.subject}\r\n`,n+="MIME-Version: 1.0\r\n",e.html&&e.text){const t=`----=_Part_${Date.now()}_${Math.random().toString(36)}`;n+=`Content-Type: multipart/alternative; boundary="${t}"\r\n\r\n`,n+=`--${t}\r\n`,n+="Content-Type: text/plain; charset=utf-8\r\n",n+="Content-Transfer-Encoding: 8bit\r\n\r\n",n+=`${e.text}\r\n\r\n`,n+=`--${t}\r\n`,n+="Content-Type: text/html; charset=utf-8\r\n",n+="Content-Transfer-Encoding: 8bit\r\n\r\n",n+=`${e.html}\r\n\r\n`,n+=`--${t}--\r\n`}else e.html?(n+="Content-Type: text/html; charset=utf-8\r\n",n+="Content-Transfer-Encoding: 8bit\r\n\r\n",n+=`${e.html}\r\n`):(n+="Content-Type: text/plain; charset=utf-8\r\n",n+="Content-Transfer-Encoding: 8bit\r\n\r\n",n+=`${e.text||""}\r\n`);return n}async saveSentMessage(e,t){try{await this.ensureRequiredConnections(!0,!1);const r=this.buildRawEmailMessage(e,t);await this.imapClient.saveMessageToFolder(r),console.error("[Email] Message saved to sent folder successfully")}catch(e){console.error("[Email] Failed to save message to sent folder:",e instanceof Error?e.message:String(e))}}async run(){const e=new t;await this.server.connect(e),console.error("MCP Mail server running on stdio")}}).run().catch(console.error);
2
+ import{Server as e}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as t}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as r,CallToolRequestSchema as n}from"@modelcontextprotocol/sdk/types.js";import s from"imap";import{EventEmitter as o}from"events";import{simpleParser as i}from"mailparser";import a from"nodemailer";class IMAPClient extends o{imap=null;config;connected=!1;authenticated=!1;currentBox=null;constructor(e){super(),this.config=e}async connect(){return new Promise((e,t)=>{console.error(`[IMAP] Connecting to ${this.config.host}:${this.config.port} (TLS: ${this.config.tls})`);const r={user:this.config.username,password:this.config.password,host:this.config.host,port:this.config.port,tls:this.config.tls||!1,connTimeout:this.config.connTimeout||1e4,authTimeout:this.config.authTimeout||5e3,keepalive:!1!==this.config.keepalive};this.imap=new s(r),this.imap.once("ready",async()=>{console.error("[IMAP] Connection ready"),this.connected=!0,this.authenticated=!0;try{await this.openBox("INBOX",!0),console.error("[IMAP] Auto-opened INBOX")}catch(e){console.error("[IMAP] Failed to auto-open INBOX:",e instanceof Error?e.message:String(e))}e()}),this.imap.once("error",e=>{console.error("[IMAP] Connection error:",e.message),t(new Error(`IMAP connection failed: ${e.message}`))}),this.imap.once("end",()=>{console.error("[IMAP] Connection ended"),this.connected=!1,this.authenticated=!1,this.currentBox=null}),this.imap.connect()})}async openBox(e="INBOX",t=!1){if(!this.imap||!this.authenticated)throw new Error("Not connected or authenticated");return new Promise((r,n)=>{this.imap.openBox(e,t,(t,s)=>{if(t)return console.error(`[IMAP] Failed to open box ${e}:`,t.message),void n(new Error(`Failed to open mailbox: ${t.message}`));console.error(`[IMAP] Opened box ${e}`),this.currentBox=e;const o={name:e,messages:{total:s.messages.total,new:s.messages.new,unseen:s.messages.unseen},permFlags:s.permFlags,uidvalidity:s.uidvalidity,uidnext:s.uidnext};r(o)})})}async getBoxes(){if(!this.imap||!this.authenticated)throw new Error("Not connected or authenticated");return new Promise((e,t)=>{this.imap.getBoxes((r,n)=>{r?t(new Error(`Failed to get boxes: ${r.message}`)):e(n)})})}async search(e=["ALL"]){if(!this.imap)throw new Error("Not connected to IMAP server");return this.currentBox||await this.openBox("INBOX",!0),new Promise((t,r)=>{this.imap.search([e],(e,n)=>{if(e)return console.error("[IMAP] Search failed:",e.message),void r(new Error(`Search failed: ${e.message}`));console.error(`[IMAP] Search found ${n.length} messages`),t(n)})})}async fetchMessages(e,t={}){if(!this.imap)throw new Error("Not connected to IMAP server");this.currentBox||await this.openBox("INBOX",!0);const r={bodies:t.bodies||["HEADER","TEXT"],struct:!1!==t.struct,envelope:!1!==t.envelope,markSeen:t.markSeen||!1,...t};return new Promise((t,n)=>{const s=[],o=new Map;if(0===e.length)return void t(s);const a=this.imap.fetch(e,r);a.on("message",(e,t)=>{console.error(`[IMAP] Processing message ${t}`);let r={},n="";const s=[],i={uid:0,id:t,flags:[],date:"",size:0};e.on("body",(e,t)=>{const o=[];e.on("data",e=>{o.push(e),s.push(e)}),e.once("end",()=>{const e=Buffer.concat(o);if("HEADER"===t.which){const t=e.toString("utf8");r=this.parseHeaders(t)}else"TEXT"===t.which&&(n=e.toString("utf8"))})}),e.once("attributes",e=>{i.uid=e.uid,i.flags=e.flags||[];const t=e.date||new Date;i.date=t.toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),i.size=e.size||0}),e.once("end",()=>{console.error(`[IMAP] Message ${t} processed, preparing for parse`),o.set(t,{message:i,headers:r,body:n,rawBuffer:Buffer.concat(s)})})}),a.once("error",e=>{console.error("[IMAP] Fetch error:",e.message),n(new Error(`Fetch failed: ${e.message}`))}),a.once("end",async()=>{console.error(`[IMAP] Fetch completed, parsing ${o.size} messages`);for(const[e,t]of o)try{const e=await i(t.rawBuffer),r=e=>e?Array.isArray(e)?e.map(e=>n(e)).filter(Boolean).join(", "):n(e):"",n=e=>{if(!e)return"";if("string"==typeof e){const t=e.match(/<([^>]+)>/)||e.match(/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:e}if(e&&"object"==typeof e){if(e.address)return e.address;if(e.text){const t=e.text.match(/<([^>]+)>/)||e.text.match(/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:e.text}}return""};s.push({...t.message,subject:e.subject||"No Subject",from:r(e.from),to:r(e.to),cc:r(e.cc)||void 0,bcc:r(e.bcc)||void 0,text:e.text,html:e.html})}catch(r){console.error(`[IMAP] Failed to parse message ${e}:`,r),s.push({...t.message,subject:t.headers.subject||"Parse Failed",from:t.headers.from||"",to:t.headers.to||"",cc:t.headers.cc||void 0,bcc:t.headers.bcc||void 0,text:t.body.trim()})}console.error(`[IMAP] All messages parsed, returning ${s.length} messages`),t(s)})})}async getMessage(e){const t=await this.fetchMessages([e]);if(0===t.length)throw new Error(`Message with UID ${e} not found`);return t[0]}async deleteMessage(e){if(!this.imap)throw new Error("Not connected to IMAP server");return this.currentBox||await this.openBox("INBOX",!1),new Promise((t,r)=>{this.imap.addFlags(e,["\\Deleted"],n=>{if(n)return console.error(`[IMAP] Failed to mark message ${e} as deleted:`,n.message),void r(new Error(`Failed to delete message: ${n.message}`));console.error(`[IMAP] Message ${e} marked for deletion`),this.imap.expunge(n=>{if(n)return console.error("[IMAP] Failed to expunge:",n.message),void r(new Error(`Failed to expunge deleted messages: ${n.message}`));console.error(`[IMAP] Message ${e} deleted successfully`),t()})})})}async getMessageCount(){return this.currentBox||await this.openBox("INBOX",!0),(await this.search(["ALL"])).length}async getUnseenMessages(){const e=await this.search(["UNSEEN"]);return this.fetchMessages(e)}async getRecentMessages(){const e=await this.search(["RECENT"]);return this.fetchMessages(e)}parseHeaders(e){const t={},r=e.split("\r\n");let n="",s="";for(const e of r)if(e.match(/^\s/)&&n)s+=" "+e.trim();else{n&&(t[n.toLowerCase()]=s.trim());const r=e.indexOf(":");r>-1?(n=e.substring(0,r).trim(),s=e.substring(r+1).trim()):(n="",s="")}return n&&(t[n.toLowerCase()]=s.trim()),t}async disconnect(){if(this.imap)return this.connected?new Promise(e=>{const t=setTimeout(()=>{console.error("[IMAP] Disconnect timeout, forcing cleanup"),this.connected=!1,this.authenticated=!1,this.currentBox=null,this.imap=null,e()},5e3);this.imap.once("end",()=>{clearTimeout(t),console.error("[IMAP] Disconnected"),this.connected=!1,this.authenticated=!1,this.currentBox=null,this.imap=null,e()}),this.imap.once("error",r=>{clearTimeout(t),console.error("[IMAP] Disconnect error:",r.message),this.connected=!1,this.authenticated=!1,this.currentBox=null,this.imap=null,e()});try{this.imap.end()}catch(r){clearTimeout(t),console.error("[IMAP] Error calling end():",r),this.connected=!1,this.authenticated=!1,this.currentBox=null,this.imap=null,e()}}):(this.imap=null,this.authenticated=!1,void(this.currentBox=null))}isConnected(){return this.connected&&this.authenticated}getCurrentBox(){return this.currentBox}getCurrentUsername(){return this.config?.username||null}async saveMessageToFolder(e,t="INBOX.Sent"){if(!this.connected)throw new Error("IMAP client is not connected");return new Promise((r,n)=>{this.imap.openBox(t,!1,s=>{s?(console.warn(`[IMAP] Folder ${t} not found, trying to create it`),this.imap.addBox(t,s=>{if(s)return console.error(`[IMAP] Failed to create folder ${t}:`,s.message),void this.trySaveToAlternateSentFolders(e,r,n);this.saveToOpenedFolder(e,t,r,n)})):this.saveToOpenedFolder(e,t,r,n)})})}saveToOpenedFolder(e,t,r,n){this.imap.append(e,{mailbox:t},e=>{e?(console.error(`[IMAP] Failed to save message to ${t}:`,e.message),n(new Error(`Failed to save message to ${t}: ${e.message}`))):r()})}trySaveToAlternateSentFolders(e,t,r){const n=["Sent","SENT","Sent Items","Sent Messages","已发送"];let s=0;const o=()=>{if(s>=n.length)return console.warn("[IMAP] All sent folder attempts failed, message not saved to sent folder"),void t();const i=n[s++];this.imap.openBox(i,!1,n=>{n?o():this.saveToOpenedFolder(e,i,t,r)})};o()}}class SMTPClient{transporter=null;config;constructor(e){this.config=e}async connect(){this.transporter=a.createTransport({host:this.config.host,port:this.config.port,secure:this.config.secure||!1,auth:{user:this.config.username,pass:this.config.password}});try{this.transporter&&await this.transporter.verify()}catch(e){throw new Error(`SMTP connection failed: ${e instanceof Error?e.message:String(e)}`)}}async sendMail(e){if(!this.transporter)throw new Error("SMTP client not connected");const t={from:e.from||this.config.username,to:Array.isArray(e.to)?e.to.join(", "):e.to,cc:e.cc?Array.isArray(e.cc)?e.cc.join(", "):e.cc:void 0,bcc:e.bcc?Array.isArray(e.bcc)?e.bcc.join(", "):e.bcc:void 0,subject:e.subject,text:e.text,html:e.html,attachments:e.attachments};try{const e=await this.transporter.sendMail(t);return{messageId:e.messageId,response:e.response,accepted:e.accepted||[],rejected:e.rejected||[]}}catch(e){throw new Error(`Failed to send email: ${e instanceof Error?e.message:String(e)}`)}}getCurrentUsername(){return this.config?.username||null}isConnected(){return null!==this.transporter}async disconnect(){if(this.transporter)try{this.transporter.close(),console.error("[SMTP] Disconnected successfully")}catch(e){console.error("[SMTP] Error during disconnect:",e instanceof Error?e.message:String(e))}finally{this.transporter=null}}}function c(e,t){const r=process.env[e];if(!r)throw new Error(`Missing required environment variable: ${e}. Please set this variable in your MCP server configuration.`);return r}function l(e){const t=process.env[e];if(!t)throw new Error(`Missing required environment variable: ${e}. Please set this variable to 'true' or 'false' in your MCP server configuration.`);if("true"!==t.toLowerCase()&&"false"!==t.toLowerCase())throw new Error(`Invalid boolean value for environment variable ${e}: ${t}. Must be 'true' or 'false'.`);return"true"===t.toLowerCase()}function d(e){const t=process.env[e];if(!t)throw new Error(`Missing required environment variable: ${e}. Please set this variable to a valid number in your MCP server configuration.`);const r=parseInt(t,10);if(isNaN(r))throw new Error(`Invalid number value for environment variable ${e}: ${t}. Must be a valid number.`);return r}const h={IMAP:{host:c("IMAP_HOST"),port:d("IMAP_PORT"),username:c("EMAIL_USER"),password:c("EMAIL_PASS"),tls:l("IMAP_SECURE")},SMTP:{host:c("SMTP_HOST"),port:d("SMTP_PORT"),username:c("EMAIL_USER"),password:c("EMAIL_PASS"),secure:l("SMTP_SECURE")}},m=["INBOX.Sent","Sent","SENT","Sent Items","Sent Messages","已发送"],u=["INBOX",...m];(new class{server;imapClient=null;smtpClient=null;isInitializing=!1;formatError(e,t){return`${t}: ${e instanceof Error?e.message:String(e)}`}isDateOnly(e){return[/^\d{4}-\d{2}-\d{2}$/,/^\d{2}-\w{3}-\d{4}$/,/^\w{3}\s+\d{1,2},?\s+\d{4}$/].some(t=>t.test(e.trim()))}filterMessagesByDateRange(e,t,r){if(!t&&!r)return e;let n=null,s=null;t&&(n=new Date(t),isNaN(n.getTime())?(console.error(`[Filter] Invalid start date format: ${t}, skipping start date filter`),n=null):console.error(`[Filter] Start date parsed as: ${n.toISOString()}`)),r&&(s=new Date(r),isNaN(s.getTime())?(console.error(`[Filter] Invalid end date format: ${r}, skipping end date filter`),s=null):this.isDateOnly(r)?(s.setHours(23,59,59,999),console.error(`[Filter] End date adjusted to end of day: ${s.toISOString()}`)):console.error(`[Filter] End date parsed as: ${s.toISOString()}`));const o=e.length,i=e.filter(e=>{if(!e.date)return!0;const t=new Date(e.date);return!(!isNaN(t.getTime())&&(n&&t<n||s&&t>s))});return console.error(`[Filter] Date filtering: ${o} -> ${i.length} messages`),i}async searchInMultipleMailboxes(e,t,r,n="",s=""){const o=["INBOX"];let i=!1;for(const e of m)try{await this.imapClient.openBox(e,!0),o.push(e),i=!0;break}catch(t){console.error(`[IMAP] Failed to open sent mailbox ${e}: ${t instanceof Error?t.message:String(t)}`)}const a={searchType:t,searchValue:r,searchCriteria:e,mailboxesSearched:[],totalMatches:0,messages:[]};for(const t of o)try{console.error(`[IMAP] Searching in mailbox: ${t}`),await this.imapClient.openBox(t,!0);const r=await this.imapClient.search(e);console.error(`[IMAP] Found ${r.length} messages in ${t}`);let o=[],i=[];if(r.length>0){console.error(`[IMAP] Auto-fetching content for ${r.length} messages from ${t}`);let e=(await this.imapClient.fetchMessages(r)).map(e=>({...e,sourceMailbox:t}));(n||s)&&(e=this.filterMessagesByDateRange(e,n,s)),o=e,i=e.map(e=>e.uid),a.messages.push(...o)}const c={mailbox:t,matchingUIDs:i,messageCount:o.length};a.mailboxesSearched.push(c)}catch(e){console.error(`[IMAP] Error searching in ${t}:`,e),a.mailboxesSearched.push({mailbox:t,error:`Failed to search: ${e instanceof Error?e.message:String(e)}`,matchingUIDs:[],messageCount:0})}if(a.totalMatches=a.messages.length,a.messages.sort((e,t)=>{const r=new Date(e.date||0);return new Date(t.date||0).getTime()-r.getTime()}),a.totalMatches>0){let e=`Found and retrieved ${a.totalMatches} messages across ${a.mailboxesSearched.length} mailboxes`;(n||s)&&(e+=" (filtered by date range)"),a.note=e}else a.note="No messages found in any of the searched mailboxes";return i||(a.warning="Could not find sent mailbox - only searched INBOX"),a}constructor(){this.validateConfig(),this.server=new e({name:"mcp-mail",version:"1.0.0"},{capabilities:{tools:{}}}),this.setupToolHandlers(),this.setupErrorHandling()}setupErrorHandling(){this.server.onerror=e=>console.error("[MCP Error]",e),process.on("SIGINT",async()=>{this.imapClient&&await this.imapClient.disconnect(),this.smtpClient&&await this.smtpClient.disconnect(),await this.server.close(),process.exit(0)})}setupToolHandlers(){this.server.setRequestHandler(r,async()=>({tools:[{name:"connect_all",description:"Connect to both IMAP and SMTP servers simultaneously",inputSchema:{type:"object",properties:{}}},{name:"list_mailboxes",description:"List all available mailboxes (folders). Auto-connects if not already connected.",inputSchema:{type:"object",properties:{}}},{name:"open_mailbox",description:"Open a specific mailbox (folder) and optionally retrieve sent mailbox info. Due to IMAP protocol limitations, only one mailbox stays open. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{mailboxName:{type:"string",description:"Name of the mailbox to open (default: INBOX)",default:"INBOX"},readOnly:{type:"boolean",description:"Open mailbox in read-only mode (default: false)",default:!1},openSent:{type:"boolean",description:"Also retrieve sent mailbox information (default: true)",default:!0}}}},{name:"get_message_count",description:"Get the total number of messages in current mailbox. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{}}},{name:"get_unseen_messages",description:"Get all unseen (unread) messages. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{}}},{name:"get_recent_messages",description:"Get all recent messages. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{}}},{name:"search_by_sender",description:"Search messages from a specific sender with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{sender:{type:"string",description:"Email address of the sender to search for"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["sender"]}},{name:"search_by_subject",description:"Search messages by subject keywords with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{subject:{type:"string",description:"Keywords to search in email subject"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["subject"]}},{name:"search_by_recipient",description:"Search messages sent to a specific recipient email address with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{recipient:{type:"string",description:"Email address of the recipient to search for"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["recipient"]}},{name:"search_since_date",description:"Search messages from a specific date until now (not for date ranges). Use search_messages for complex date ranges.",inputSchema:{type:"object",properties:{date:{type:"string",description:'Start date to search from (searches from this date to present). Formats: "April 20, 2010", "20-Apr-2010", or "2010-04-20"'}},required:["date"]}},{name:"search_unread_from_sender",description:"Search unread messages from a specific sender with optional date range (demonstrates AND logic). Auto-connects if not already connected.",inputSchema:{type:"object",properties:{sender:{type:"string",description:"Email address of the sender"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["sender"]}},{name:"search_by_body",description:"Search messages containing specific text in the body with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{text:{type:"string",description:"Text to search for in message body"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["text"]}},{name:"search_with_keyword",description:"Search messages with specific keyword/flag with optional date range. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{keyword:{type:"string",description:"Keyword to search for"},startDate:{type:"string",description:'Optional start date/time for filtering. Supports multiple formats: "2025-07-01", "2025-07-01 14:30:00", "01-Jul-2025", or ISO format. Leave empty to not filter by start date.'},endDate:{type:"string",description:'Optional end date/time for filtering. Supports multiple formats: "2025-08-01", "2025-08-01 23:59:59", "01-Aug-2025", or ISO format. Leave empty to not filter by end date.'}},required:["keyword"]}},{name:"get_messages",description:"Retrieve multiple messages by their UIDs. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{uids:{type:"array",description:"Array of message UIDs to retrieve",items:{type:"number"}},markSeen:{type:"boolean",description:"Mark messages as seen when retrieving (default: false)",default:!1}},required:["uids"]}},{name:"get_message",description:"Retrieve a specific email message by UID. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{uid:{type:"number",description:"Message UID to retrieve"},markSeen:{type:"boolean",description:"Mark message as seen when retrieving (default: false)",default:!1}},required:["uid"]}},{name:"send_email",description:"Send an email via SMTP. Auto-connects to SMTP server if not already connected.",inputSchema:{type:"object",properties:{to:{type:"string",description:"Recipient email address(es), comma-separated"},subject:{type:"string",description:"Email subject"},text:{type:"string",description:"Plain text email body"},html:{type:"string",description:"HTML email body (optional)"},cc:{type:"string",description:"CC recipients, comma-separated (optional)"},bcc:{type:"string",description:"BCC recipients, comma-separated (optional)"}},required:["to","subject"]}},{name:"reply_to_email",description:"Reply to a specific email by UID. Automatically sets reply headers, adds Re: prefix, and includes original message. Auto-connects to both IMAP and SMTP if not already connected.",inputSchema:{type:"object",properties:{originalUid:{type:"number",description:"UID of the original message to reply to"},text:{type:"string",description:"Reply message text"},html:{type:"string",description:"Reply message HTML (optional)"},replyToAll:{type:"boolean",description:"Reply to all recipients instead of just sender (default: false)",default:!1},includeOriginal:{type:"boolean",description:"Include original message in reply (default: true)",default:!0}},required:["originalUid"]}},{name:"delete_message",description:"Delete a specific email message by UID. Auto-connects if not already connected.",inputSchema:{type:"object",properties:{uid:{type:"number",description:"Message UID to delete"}},required:["uid"]}},{name:"get_connection_status",description:"Check the current connection status of both IMAP and SMTP servers.",inputSchema:{type:"object",properties:{}}},{name:"disconnect_all",description:"Disconnect from both IMAP and SMTP servers. Only disconnects if currently connected.",inputSchema:{type:"object",properties:{}}}]})),this.server.setRequestHandler(n,async e=>{const{name:t,arguments:r}=e.params;try{switch(t){case"open_mailbox":return await this.handleOpenMailbox(r||{});case"list_mailboxes":return await this.handleListMailboxes();case"search_by_sender":return await this.handleSearchBySender(r||{});case"search_by_subject":return await this.handleSearchBySubject(r);case"search_by_recipient":return await this.handleSearchByRecipient(r);case"search_since_date":return await this.handleSearchSinceDate(r);case"search_unread_from_sender":return await this.handleSearchUnreadFromSender(r);case"search_by_body":return await this.handleSearchByBody(r);case"search_with_keyword":return await this.handleSearchWithKeyword(r);case"get_messages":return await this.handleGetMessages(r);case"get_message":return await this.handleGetMessage(r);case"delete_message":return await this.handleDeleteMessage(r);case"get_message_count":return await this.handleGetMessageCount();case"get_unseen_messages":return await this.handleGetUnseenMessages();case"get_recent_messages":return await this.handleGetRecentMessages();case"get_connection_status":return await this.handleGetConnectionStatus();case"send_email":return await this.handleSendEmail(r);case"reply_to_email":return await this.handleReplyToEmail(r);case"connect_all":return await this.handleConnectAll();case"disconnect_all":return await this.handleDisconnectAll();default:throw new Error(`Unknown tool: ${t}`)}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:String(e)}`}]}}})}async ensureIMAPConnection(){if(!this.imapClient||!this.imapClient.isConnected())if(this.isInitializing)for(;this.isInitializing;)await new Promise(e=>setTimeout(e,100));else{this.isInitializing=!0;try{const e=h.IMAP;console.error(`[IMAP] Auto-connecting to ${e.host}:${e.port}`),this.imapClient=new IMAPClient(e),await this.imapClient.connect(),console.error("[IMAP] Auto-connection successful")}finally{this.isInitializing=!1}}}async ensureSMTPConnection(){if(this.smtpClient)return;const e=h.SMTP;console.error(`[SMTP] Auto-connecting to ${e.host}:${e.port}`),this.smtpClient=new SMTPClient(e),await this.smtpClient.connect(),console.error("[SMTP] Auto-connection successful")}async ensureRequiredConnections(e=!1,t=!1){e&&await this.ensureIMAPConnection(),t&&await this.ensureSMTPConnection()}async handleOpenMailbox(e){await this.ensureRequiredConnections(!0,!1);const t=e.mailboxName||"INBOX",r=e.readOnly||!1,n=!1!==e.openSent;try{const e={},s=await this.imapClient.openBox(t,r);if(e[t]=s,e.currentlyOpen=t,n&&"INBOX.Sent"!==t&&"Sent"!==t&&"SENT"!==t)try{const n=["INBOX.Sent","Sent","SENT","Sent Items","Sent Messages","已发送"];let s=!1;for(const o of n)try{const n=await this.imapClient.openBox(o,!0);e[o]=n,s=!0,await this.imapClient.openBox(t,r),e.currentlyOpen=t,e.note=`Retrieved info from both ${t} and ${o}. Currently open: ${t}`;break}catch(e){console.error(`[IMAP] Failed to open sent mailbox ${o}: ${e instanceof Error?e.message:String(e)}`)}s||(e.sentBoxWarning="Could not find any sent mailbox")}catch(t){e.sentBoxError=`Failed to access sent mailbox: ${t instanceof Error?t.message:String(t)}`}return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to open mailbox"))}}async handleListMailboxes(){await this.ensureRequiredConnections(!0,!1);try{const e=await this.imapClient.getBoxes(),t=(e,r="",n=new Set)=>{if(n.has(e))return{name:r,circular:!0};n.add(e);const s={name:r,attribs:e.attribs||[],delimiter:e.delimiter||".",selectable:!e.attribs?.includes("\\Noselect")};if(e.children&&Object.keys(e.children).length>0){s.children={};for(const[o,i]of Object.entries(e.children)){const a=r?`${r}${e.delimiter||"."}${o}`:o;s.children[o]=t(i,a,new Set(n))}}return n.delete(e),s},r={};for(const[n,s]of Object.entries(e))r[n]=t(s,n);return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to list mailboxes"))}}async handleSearchBySender(e){await this.ensureRequiredConnections(!0,!1);const t=e.sender,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("sender parameter is required");try{const e=["FROM",t];console.error("[IMAP] Searching messages from sender across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"By Sender",t,r,n);return s.sender=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search by sender failed"))}}async handleSearchBySubject(e){await this.ensureRequiredConnections(!0,!1);const t=e.subject,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("subject parameter is required");try{const e=["SUBJECT",t];console.error("[IMAP] Searching messages with subject across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"By Subject",t,r,n);return s.subjectKeywords=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search by subject failed"))}}async handleSearchByRecipient(e){await this.ensureRequiredConnections(!0,!1);const t=e.recipient,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("recipient parameter is required");try{const e=["TO",t];console.error("[IMAP] Searching messages to recipient across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"By Recipient",t,r,n);return s.recipient=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search by recipient failed"))}}async handleSearchSinceDate(e){await this.ensureRequiredConnections(!0,!1);const t=e.date;if(!t)throw new Error("date parameter is required");try{const e=["SINCE",t];console.error("[IMAP] Searching messages since date across all mailboxes:",t);const r=await this.searchInMultipleMailboxes(e,"Since Date",t);return r.sinceDate=t,r.note='Date format should be like "April 20, 2010" or "20-Apr-2010". Searched across multiple mailboxes.',{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search since date failed"))}}async handleSearchUnreadFromSender(e){await this.ensureRequiredConnections(!0,!1);const t=e.sender,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("sender parameter is required");try{const e=["UNSEEN",["FROM",t]];console.error("[IMAP] Searching unread messages from sender across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"Unread messages from specific sender",t,r,n);return s.sender=t,r&&(s.startDate=r),n&&(s.endDate=n),s.note="By default, all criteria are ANDed together - finds messages that are BOTH unread AND from the specified sender. Searched across multiple mailboxes.",{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search unread from sender failed"))}}async handleSearchByBody(e){await this.ensureRequiredConnections(!0,!1);const t=e.text,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("text parameter is required");try{const e=["BODY",t];console.error("[IMAP] Searching messages with body text across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"By Body Text",t,r,n);return s.bodyText=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search by body failed"))}}async handleSearchWithKeyword(e){await this.ensureRequiredConnections(!0,!1);const t=e.keyword,r=e.startDate||"",n=e.endDate||"";if(!t)throw new Error("keyword parameter is required");try{const e=["KEYWORD",t];console.error("[IMAP] Searching messages with keyword across all mailboxes:",t);const s=await this.searchInMultipleMailboxes(e,"With Keyword",t,r,n);return s.keyword=t,r&&(s.startDate=r),n&&(s.endDate=n),{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Search with keyword failed"))}}async handleGetMessages(e){await this.ensureRequiredConnections(!0,!1);const t=e.uids;if(!Array.isArray(t))throw new Error("uids must be an array of numbers");const r=e.markSeen||!1;try{const e=await this.imapClient.fetchMessages(t,{markSeen:r});return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to get messages"))}}async handleGetMessage(e){await this.ensureRequiredConnections(!0,!1);const t=e.uid;if("number"!=typeof t)throw new Error("uid must be a number");try{const e=await this.imapClient.getMessage(t);return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to get message"))}}async handleDeleteMessage(e){await this.ensureRequiredConnections(!0,!1);const t=e.uid;if("number"!=typeof t)throw new Error("uid must be a number");try{return await this.imapClient.deleteMessage(t),{content:[{type:"text",text:`Message with UID ${t} deleted successfully`}]}}catch(e){throw new Error(this.formatError(e,"Failed to delete message"))}}async handleGetMessageCount(){await this.ensureRequiredConnections(!0,!1);try{return{content:[{type:"text",text:`Total messages: ${await this.imapClient.getMessageCount()}`}]}}catch(e){throw new Error(this.formatError(e,"Failed to get message count"))}}async handleGetUnseenMessages(){await this.ensureRequiredConnections(!0,!1);try{const e=await this.imapClient.getUnseenMessages();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to get unseen messages"))}}async handleGetRecentMessages(){await this.ensureRequiredConnections(!0,!1);try{const e=await this.imapClient.getRecentMessages();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to get recent messages"))}}async handleGetConnectionStatus(){const e={timestamp:(new Date).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),connections:{imap:{connected:!1,currentBox:null,serverInfo:`${h.IMAP.host}:${h.IMAP.port}`,username:h.IMAP.username,tls:h.IMAP.tls,status:"Not connected"},smtp:{connected:!1,serverInfo:`${h.SMTP.host}:${h.SMTP.port}`,username:h.SMTP.username,secure:h.SMTP.secure,status:"Not connected"}}};return this.imapClient&&(e.connections.imap.connected=this.imapClient.isConnected(),e.connections.imap.currentBox=this.imapClient.getCurrentBox(),e.connections.imap.connected?e.connections.imap.status=e.connections.imap.currentBox?`Connected - Current mailbox: ${e.connections.imap.currentBox}`:"Connected - No mailbox open":e.connections.imap.status="Connection lost or failed"),this.smtpClient&&(e.connections.smtp.connected=!0,e.connections.smtp.status="Connected and ready"),{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}async handleSendEmail(e){await this.ensureRequiredConnections(!1,!0);const t={to:e.to.split(",").map(e=>e.trim()),subject:e.subject,text:e.text,html:e.html,cc:e.cc?e.cc.split(",").map(e=>e.trim()):void 0,bcc:e.bcc?e.bcc.split(",").map(e=>e.trim()):void 0};if(!t.text&&!t.html)throw new Error("Either text or html content is required");try{const e=await this.smtpClient.sendMail(t);await this.saveSentMessage(t,e.messageId);const r={...e,sentFolderSaved:!0,note:"Email sent successfully and saved to sent folder"};return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to send email"))}}async handleReplyToEmail(e){await this.ensureRequiredConnections(!0,!0);const t=e.originalUid,r=e.text,n=e.html,s=e.replyToAll||!1,o=!1!==e.includeOriginal;if("number"!=typeof t)throw new Error("originalUid must be a number");try{await this.ensureMailboxOpen(),console.error(`[Reply] Fetching original message with UID: ${t}`);const e=await this.findMessageInMultipleMailboxes(t);if(!e)throw new Error(`Original message with UID ${t} not found in any mailbox`);const i=this.extractEmailFromAddress(e.from);if(!i)throw new Error("Could not extract sender email from original message");let a=[i],c=[];if(s){const t=this.extractEmailsFromAddressField(e.to),r=this.extractEmailsFromAddressField(e.cc),n=[...t,...r].filter(e=>e!==h.IMAP.username&&e!==i);n.length>0&&(c=n)}let l=e.subject||"";l.toLowerCase().startsWith("re:")||(l=`Re: ${l}`);let d=r,m=n;if(o&&e){const t=e.date?new Date(e.date).toLocaleString():"Unknown Date",s=e.from||"Unknown Sender";if(d=`${r}\n\n${this.buildQuotedText(e.text||"",t,s)}`,n||e.html){const o=this.buildQuotedHtml(e.html||e.text||"",t,s);m=`${n||this.textToHtml(r)}<br><br>${o}`}}const u={to:a,cc:c.length>0?c:void 0,subject:l,text:d,html:m};console.error(`[Reply] Sending reply to: ${a.join(", ")}${c.length>0?` (CC: ${c.join(", ")})`:""}`);const p=await this.smtpClient.sendMail(u);await this.saveSentMessage(u,p.messageId);const g={originalUid:t,originalFrom:i,originalSubject:e.subject,replyToAll:s,includeOriginal:o,recipients:{to:a,cc:c.length>0?c:void 0}},f={...p,replyInfo:g,sentFolderSaved:!0,note:"Reply sent successfully and saved to sent folder"};return{content:[{type:"text",text:JSON.stringify(f,null,2)}]}}catch(e){throw new Error(this.formatError(e,"Failed to reply to email"))}}extractEmailFromAddress(e){if(!e)return null;if(Array.isArray(e)&&e.length>0)return e[0].address||e[0];if("string"==typeof e){const t=e.match(/<([^>]+)>/)||e.match(/([^\s<>]+@[^\s<>]+)/);return t?t[1]:e}return e.address||null}extractEmailsFromAddressField(e){if(!e)return[];if(Array.isArray(e))return e.map(e=>e.address||e).filter(Boolean);if("string"==typeof e)return e.split(",").map(e=>{const t=e.trim().match(/<([^>]+)>/)||e.trim().match(/([^\s<>]+@[^\s<>]+)/);return t?t[1]:e.trim()}).filter(Boolean);const t=this.extractEmailFromAddress(e);return t?[t]:[]}buildQuotedText(e,t,r){return`On ${t}, ${r} wrote:\n${e.split("\n").map(e=>`> ${e}`).join("\n")}`}buildQuotedHtml(e,t,r){return`<div style="border-left: 3px solid #ccc; padding-left: 10px; margin-left: 10px; color: #666;">\n <p><strong>On ${t}, ${r} wrote:</strong></p>\n <div>${e.replace(/\n/g,"<br>")}</div>\n </div>`}textToHtml(e){return e.replace(/\n/g,"<br>").replace(/ /g,"&nbsp;&nbsp;")}async findMessageInMultipleMailboxes(e){if(this.imapClient.getCurrentBox())try{return await this.imapClient.getMessage(e)}catch(e){console.error(`[Search] Message not found in current mailbox: ${e instanceof Error?e.message:String(e)}`)}for(const t of u)try{await this.imapClient.openBox(t,!0);const r=await this.imapClient.getMessage(e);return console.error(`[Search] Found message in mailbox: ${t}`),r}catch(e){console.error(`[Search] Message not found in ${t}: ${e instanceof Error?e.message:String(e)}`)}return null}async ensureMailboxOpen(e="INBOX"){this.imapClient.getCurrentBox()||(console.error(`[IMAP] No mailbox currently open, opening ${e}`),await this.imapClient.openBox(e,!0))}async handleConnectAll(){const e=[];try{if(this.imapClient&&this.imapClient.isConnected()){const t=this.imapClient.getCurrentUsername(),r=h.IMAP.username;t!==r?(console.error(`[IMAP] User mismatch: current=${t}, config=${r}, reconnecting...`),await this.imapClient.disconnect(),await this.ensureIMAPConnection(),e.push("✅ IMAP: Reconnected with correct user")):e.push("ℹ️ IMAP: Already connected")}else await this.ensureIMAPConnection(),e.push("✅ IMAP: Connected successfully")}catch(t){e.push(`❌ IMAP: Connection failed - ${t instanceof Error?t.message:String(t)}`)}try{if(this.smtpClient&&this.smtpClient.isConnected()){const t=this.smtpClient.getCurrentUsername(),r=h.SMTP.username;t!==r?(console.error(`[SMTP] User mismatch: current=${t}, config=${r}, reconnecting...`),await this.smtpClient.disconnect(),await this.ensureSMTPConnection(),e.push("✅ SMTP: Reconnected with correct user")):e.push("ℹ️ SMTP: Already connected")}else await this.ensureSMTPConnection(),e.push("✅ SMTP: Connected successfully")}catch(t){e.push(`❌ SMTP: Connection failed - ${t instanceof Error?t.message:String(t)}`)}return{content:[{type:"text",text:e.join("\n")}]}}async handleDisconnectAll(){const e=[];if(this.imapClient)try{await this.imapClient.disconnect(),this.imapClient=null,e.push("✅ IMAP: Disconnected successfully")}catch(t){e.push(`❌ IMAP: Disconnect failed - ${t instanceof Error?t.message:String(t)}`)}else e.push("ℹ️ IMAP: Not connected");if(this.smtpClient)try{await this.smtpClient.disconnect(),this.smtpClient=null,e.push("✅ SMTP: Disconnected successfully")}catch(t){e.push(`❌ SMTP: Disconnect failed - ${t instanceof Error?t.message:String(t)}`)}else e.push("ℹ️ SMTP: Not connected");return{content:[{type:"text",text:e.join("\n")}]}}validateConfig(){try{console.error("=== MCP Mail Server Configuration ==="),console.error(`IMAP: ${h.IMAP.host}:${h.IMAP.port} (TLS: ${h.IMAP.tls})`),console.error(`SMTP: ${h.SMTP.host}:${h.SMTP.port} (Secure: ${h.SMTP.secure})`),console.error(`User: ${h.IMAP.username}`),console.error("Password: [CONFIGURED]"),console.error("Configuration loaded successfully")}catch(e){throw console.error("Configuration error:",e instanceof Error?e.message:String(e)),console.error("Please ensure all required environment variables are set in your MCP server configuration."),e}}buildRawEmailMessage(e,t){const r=(new Date).toUTCString();let n="";if(n+=`Message-ID: ${t||`<${Date.now()}.${Math.random().toString(36)}@${h.IMAP.host}>`}\r\n`,n+=`Date: ${r}\r\n`,n+=`From: ${h.IMAP.username}\r\n`,n+=`To: ${Array.isArray(e.to)?e.to.join(", "):e.to}\r\n`,e.cc&&(n+=`Cc: ${Array.isArray(e.cc)?e.cc.join(", "):e.cc}\r\n`),e.bcc&&(n+=`Bcc: ${Array.isArray(e.bcc)?e.bcc.join(", "):e.bcc}\r\n`),n+=`Subject: ${e.subject}\r\n`,n+="MIME-Version: 1.0\r\n",e.html&&e.text){const t=`----=_Part_${Date.now()}_${Math.random().toString(36)}`;n+=`Content-Type: multipart/alternative; boundary="${t}"\r\n\r\n`,n+=`--${t}\r\n`,n+="Content-Type: text/plain; charset=utf-8\r\n",n+="Content-Transfer-Encoding: 8bit\r\n\r\n",n+=`${e.text}\r\n\r\n`,n+=`--${t}\r\n`,n+="Content-Type: text/html; charset=utf-8\r\n",n+="Content-Transfer-Encoding: 8bit\r\n\r\n",n+=`${e.html}\r\n\r\n`,n+=`--${t}--\r\n`}else e.html?(n+="Content-Type: text/html; charset=utf-8\r\n",n+="Content-Transfer-Encoding: 8bit\r\n\r\n",n+=`${e.html}\r\n`):(n+="Content-Type: text/plain; charset=utf-8\r\n",n+="Content-Transfer-Encoding: 8bit\r\n\r\n",n+=`${e.text||""}\r\n`);return n}async saveSentMessage(e,t){try{await this.ensureRequiredConnections(!0,!1);const r=this.buildRawEmailMessage(e,t);await this.imapClient.saveMessageToFolder(r),console.error("[Email] Message saved to sent folder successfully")}catch(e){console.error("[Email] Failed to save message to sent folder:",e instanceof Error?e.message:String(e))}}async run(){const e=new t;await this.server.connect(e),console.error("MCP Mail server running on stdio")}}).run().catch(console.error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-mail-server",
3
- "version": "1.1.5",
3
+ "version": "1.1.6",
4
4
  "description": "MCP server for IMAP/SMTP email access with environment-based configuration",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",