### Get Folders Source: https://context7.com/exerra/cf-imap/llms.txt Lists all folders within a specified namespace, including their attributes and hierarchy delimiters. Supports wildcard filtering. ```APIDOC ## Get Folders ### Description Lists all folders within a specified namespace along with their attributes and hierarchy delimiters. Supports filtering with wildcards. ### Method `getFolders(namespace: string, filter?: string)` ### Endpoint N/A (Client-side operation within Workers) ### Parameters #### Path Parameters None #### Query Parameters None #### Method Parameters - **namespace** (string) - Required - The namespace to list folders from (e.g., the personal namespace prefix). - **filter** (string) - Optional - A wildcard string to filter folder names (e.g., `"*"`, `"INBOX.*"`). Defaults to `"*"`. ### Request Example ```typescript // Assuming imap is connected and namespaces are retrieved const namespace = namespaces[0]; // e.g., "INBOX" const folders = await imap.getFolders(namespace, "*"); ``` ### Response #### Success Response (200) - **folders** (Array) - An array of folder objects. - **name** (string) - The name of the folder. - **delimiter** (string) - The hierarchy delimiter for the folder (e.g., `/`). - **attributes** (Array) - Attributes of the folder (e.g., `["HasNoChildren", "Sent"]`). #### Response Example ```json [ { "name": "INBOX", "delimiter": "/", "attributes": ["HasNoChildren"] }, { "name": "Sent", "delimiter": "/", "attributes": ["HasNoChildren", "Sent"] } ] ``` #### Error Response (500) - **message** (string) - Description of the error during folder listing. ``` -------------------------------- ### Get Namespaces Source: https://context7.com/exerra/cf-imap/llms.txt Retrieves the prefix and hierarchy delimiter for personal and shared namespaces accessible to the authenticated user. Must be called after connecting. ```APIDOC ## Get Namespaces ### Description Returns the prefix and hierarchy delimiter for personal and shared namespaces accessible to the authenticated user. Should be called after connecting. ### Method `getNamespaces()` ### Endpoint N/A (Client-side operation within Workers) ### Parameters #### Method Parameters None ### Request Example ```typescript // Assuming imap is already connected const namespaces = await imap.getNamespaces() // namespaces might be: ["INBOX", ""] ``` ### Response #### Success Response (200) - **namespaces** (Array) - An array where the first element is the personal namespace prefix and the second is the shared namespace prefix (often empty). #### Response Example ```json ["INBOX", ""] ``` #### Error Response (500) - **message** (string) - Description of the error during namespace retrieval. ``` -------------------------------- ### Get IMAP Folders with CF-Imap Source: https://context7.com/exerra/cf-imap/llms.txt Lists all folders within a specified IMAP namespace, including their attributes and hierarchy delimiters. This function can utilize wildcards for filtering. The response is a JSON array of folder objects. The connection is logged out in the finally block. ```typescript export default { async fetch(request: Request): Promise { try { await imap.connect() const namespaces = await imap.getNamespaces() const folders = await imap.getFolders(namespaces[0], "*") // Returns: [ // { name: "INBOX", delimiter: "/", attributes: ["HasNoChildren"] }, // { name: "Sent", delimiter: "/", attributes: ["HasNoChildren", "Sent"] } // ] return new Response(JSON.stringify(folders, null, 2), { headers: { "Content-Type": "application/json" } }) } catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }) } finally { await imap.logout() } } } ``` -------------------------------- ### Get IMAP Namespaces with CF-Imap Source: https://context7.com/exerra/cf-imap/llms.txt Retrieves IMAP namespaces (personal and shared) accessible to the authenticated user after establishing a connection. The result is an array containing namespace prefixes and hierarchy delimiters. The connection is logged out in the finally block. ```typescript export default { async fetch(request: Request): Promise { try { await imap.connect() const namespaces = await imap.getNamespaces() // Returns array like: ["INBOX", ""] return new Response(JSON.stringify(namespaces), { headers: { "Content-Type": "application/json" } }) } catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }) } finally { await imap.logout() } } } ``` -------------------------------- ### Initialize CFImap Client and Connect Source: https://github.com/exerra/cf-imap/blob/main/README.md Initializes the `CFImap` client with host, port, TLS settings, and authentication credentials. The `connect()` function should be called within a request handler in Cloudflare Workers due to runtime limitations. ```typescript import { CFImap } from "cf-imap" const imap = new CFImap({ host: "mail.example.com", port: 993, tls: true, auth: { username: "user@example.com", password: "pa$$w0rd" } }) const handleRequest = async () => { await imap.connect() } ``` -------------------------------- ### Select Folder Source: https://context7.com/exerra/cf-imap/llms.txt Selects a specific folder for subsequent operations, returning metadata about the folder such as email count and available flags. ```APIDOC ## Select Folder ### Description Selects a specific folder for subsequent operations like fetching or searching emails. Returns metadata about the folder including email count and available flags. ### Method `selectFolder(folderName: string)` ### Endpoint N/A (Client-side operation within Workers) ### Parameters #### Method Parameters - **folderName** (string) - Required - The name of the folder to select (e.g., `"INBOX"`). ### Request Example ```typescript // Assuming imap is connected const metadata = await imap.selectFolder("INBOX"); ``` ### Response #### Success Response (200) - **metadata** (object) - An object containing folder metadata. - **emails** (number) - The total number of emails in the folder. - **recent** (number) - The number of recent emails. - **flags** (Array) - Flags available on emails in this folder. - **permanentFlags** (Array) - Permanent flags that can be set on emails. - **uidvalidity** (number) - The validity of UIDs for this folder. - **uidnext** (number) - The next available UID for new messages. #### Response Example ```json { "emails": 42, "recent": 5, "flags": ["Answered", "Flagged", "Deleted", "Seen", "Draft"], "permanentFlags": ["Answered", "Flagged", "Deleted", "Seen", "Draft"], "uidvalidity": 1234567890, "uidnext": 43 } ``` #### Error Response (500) - **message** (string) - Description of the error when selecting the folder. ``` -------------------------------- ### Search and Fetch Emails by Criteria (TypeScript) Source: https://context7.com/exerra/cf-imap/llms.txt Combines IMAP search and fetch operations to retrieve specific emails from the INBOX folder that are unread and sent within the last week. It first connects, selects the INBOX, searches for matching email IDs, fetches the full email content for those IDs, filters the results, and returns a JSON summary of the found emails. Requires an active IMAP connection and the 'imap' library. ```typescript export default { async fetch(request: Request): Promise { try { await imap.connect() await imap.selectFolder("INBOX") // Find unread emails from the last week const oneWeekAgo = new Date() oneWeekAgo.setDate(oneWeekAgo.getDate() - 7) const unreadIds = await imap.searchEmails({ seen: false, since: oneWeekAgo }) if (unreadIds.length === 0) { return new Response("No unread emails found") } // Fetch the found emails const emails = await imap.fetchEmails({ folder: "INBOX", limit: [Math.min(...unreadIds), Math.max(...unreadIds)], fetchBody: true, peek: true }) // Filter to only the IDs we found (in case range includes others) const filteredEmails = emails.filter(email => unreadIds.includes(parseInt(email.messageID)) ) const summary = filteredEmails.map(e => ({ from: e.from, subject: e.subject, date: e.date.toISOString() })) return new Response(JSON.stringify(summary, null, 2), { headers: { "Content-Type": "application/json" } }) } catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }) } finally { await imap.logout() } } } ``` -------------------------------- ### Fetch Emails Source: https://context7.com/exerra/cf-imap/llms.txt Retrieves emails from the selected folder with customizable options including range selection, body fetching, and peek mode to avoid marking emails as read. ```APIDOC ## Fetch Emails ### Description Retrieves emails from the selected folder with customizable options including range selection, body fetching, and peek mode to avoid marking emails as read. ### Method GET ### Endpoint /fetch-emails ### Parameters #### Query Parameters - **folder** (string) - Optional - The folder to retrieve emails from (e.g., "INBOX"). Defaults to "INBOX". - **limit** (array of two numbers) - Optional - Specifies a range of emails to fetch (e.g., `[1, 5]` for the first 5 emails). - **fetchBody** (boolean) - Optional - If true, the body of the email will be fetched. Defaults to false. - **peek** (boolean) - Optional - If true, emails will not be marked as read after fetching. Defaults to false. ### Request Example This endpoint is typically called internally by the `fetch` function in the provided code. A direct HTTP request would not be structured this way. ### Response #### Success Response (200) - **from** (string) - The sender's email address. - **subject** (string) - The subject of the email. - **date** (string) - The date the email was sent, in ISO format. - **bodyPreview** (string) - A preview of the email body (first 100 characters). #### Response Example ```json [ { "from": "sender@example.com", "subject": "Email Subject", "date": "2024-01-01T12:00:00.000Z", "bodyPreview": "Email body content..." } ] ``` ``` -------------------------------- ### Connect to IMAP Server with CF-Imap Source: https://context7.com/exerra/cf-imap/llms.txt Establishes a connection to an IMAP server using CF-Imap. This function requires authentication details and must be called within a Cloudflare Workers request handler due to platform limitations. It returns a response indicating connection success or failure. ```typescript import { CFImap } from "cf-imap" const imap = new CFImap({ host: "imap.gmail.com", port: 993, tls: true, auth: { username: "user@gmail.com", password: "app_password_here" } }) export default { async fetch(request: Request): Promise { try { await imap.connect() return new Response("Connected successfully") } catch (error) { return new Response(`Connection failed: ${error.message}`, { status: 500 }) } } } ``` -------------------------------- ### Connect to IMAP Server Source: https://context7.com/exerra/cf-imap/llms.txt Establishes a connection to an IMAP server with authentication. This function must be called within a Cloudflare Workers request handler. ```APIDOC ## Connect to IMAP Server ### Description Establishes a connection to an IMAP server with authentication. This must be called inside a request handler due to Cloudflare Workers platform limitations on async operations outside handlers. ### Method Implicit (Instantiated and `connect()` called) ### Endpoint N/A (Client-side operation within Workers) ### Parameters #### Constructor Parameters - **host** (string) - Required - The hostname of the IMAP server. - **port** (number) - Required - The port for the IMAP server (e.g., 993 for TLS, 143 for non-TLS). - **tls** (boolean) - Required - Set to `true` for TLS connections, `false` otherwise. - **auth** (object) - Required - Authentication credentials. - **username** (string) - Required - The IMAP username. - **password** (string) - Required - The IMAP password or app-specific password. #### `connect()` Method Parameters None ### Request Example ```typescript import { CFImap } from "cf-imap" const imap = new CFImap({ host: "imap.gmail.com", port: 993, tls: true, auth: { username: "user@gmail.com", password: "app_password_here" } }) // Inside a fetch handler: await imap.connect() ``` ### Response #### Success Response (200) Connection established. #### Response Example (No direct response body, indicates successful connection via `await imap.connect()` resolving) #### Error Response (500) - **message** (string) - Description of the connection error. ``` -------------------------------- ### Request IMAP Server Housekeeping (TypeScript) Source: https://context7.com/exerra/cf-imap/llms.txt Initiates a checkpoint operation on the IMAP server, which is a housekeeping task for server maintenance. This function connects to the server, selects a folder, calls the 'check' method, and returns the server's response strings. It's useful for ensuring server integrity and is compliant with RFC 3501. Requires an active IMAP connection. ```typescript export default { async fetch(request: Request): Promise { try { await imap.connect() await imap.selectFolder("INBOX") const responses = await imap.check() // Returns array of server response strings return new Response(JSON.stringify(responses), { headers: { "Content-Type": "application/json" } }) } catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }) } finally { await imap.logout() } } } ``` -------------------------------- ### Fetch Emails from IMAP Folder Source: https://context7.com/exerra/cf-imap/llms.txt Retrieves emails from a specified IMAP folder. Supports fetching email bodies, setting limits for the number of emails, and using peek mode to prevent marking emails as read. It returns a simplified array of email objects, including sender, subject, date, and a preview of the body. ```typescript export default { async fetch(request: Request): Promise { try { await imap.connect() await imap.selectFolder("INBOX") // Fetch the 5 most recent emails with bodies, without marking as read const emails = await imap.fetchEmails({ folder: "INBOX", limit: [1, 5], fetchBody: true, peek: true }) // emails is array of: // { // from: "sender@example.com", // to: "recipient@example.com", // subject: "Email Subject", // messageID: "", // contentType: "text/plain; charset=UTF-8", // date: Date object, // body: "Email body content...", // raw: "Full raw email response" // } const simplified = emails.map(e => ({ from: e.from, subject: e.subject, date: e.date.toISOString(), bodyPreview: e.body.substring(0, 100) })) return new Response(JSON.stringify(simplified, null, 2), { headers: { "Content-Type": "application/json" } }) } catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }) } finally { await imap.logout() } } } ``` -------------------------------- ### Search Emails Source: https://context7.com/exerra/cf-imap/llms.txt Searches for emails matching specified criteria using IMAP search commands. Returns an array of email IDs that can be used with fetchEmails. ```APIDOC ## Search Emails ### Description Searches for emails matching specified criteria using IMAP search commands. Returns an array of email IDs that can be used with fetchEmails. ### Method GET ### Endpoint /search-emails ### Parameters #### Query Parameters - **folder** (string) - Optional - The folder to search within. Defaults to "INBOX". - **seen** (boolean) - Optional - Filters for seen (true) or unseen (false) emails. - **from** (string) - Optional - Filters emails from a specific sender. - **subject** (string) - Optional - Filters emails with a subject containing the specified text. - **recent** (boolean) - Optional - Filters for recent emails. - **largerThan** (number) - Optional - Filters for emails larger than the specified size in bytes. - **since** (string) - Optional - Filters emails sent on or after this date (YYYY-MM-DD). - **before** (string) - Optional - Filters emails sent on or before this date (YYYY-MM-DD). - **all** (boolean) - Optional - If true, returns all email IDs in the folder. ### Request Example This endpoint is typically called internally by the `fetch` function in the provided code. A direct HTTP request would not be structured this way. ### Response #### Success Response (200) - **unseen** (array of strings) - Email IDs of unseen emails. - **withSubject** (array of strings) - Email IDs of emails with the specified subject. - **recentLarge** (array of strings) - Email IDs of recent, large emails. - **dateRange** (array of strings) - Email IDs of emails within the specified date range. - **all** (array of strings) - All email IDs in the folder. #### Response Example ```json { "unseen": [ "", "" ], "withSubject": [ "" ], "recentLarge": [ "" ], "dateRange": [ "" ], "all": [ "", "", "", "", "" ] } ``` ``` -------------------------------- ### Complete Email Processing Workflow on Cloudflare Workers Source: https://context7.com/exerra/cf-imap/llms.txt This TypeScript code demonstrates a complete email processing workflow within a Cloudflare Worker. It utilizes the 'cf-imap' library to connect to an IMAP server, authenticate, select the inbox, search for unread emails, fetch email headers, process the data, and return a JSON response. It includes comprehensive error handling and ensures the IMAP connection is properly closed. ```typescript import { CFImap } from "cf-imap" export default { async fetch(request: Request): Promise { const imap = new CFImap({ host: "imap.example.com", port: 993, tls: true, auth: { username: "monitor@example.com", password: "secure_password" } }) try { // Connect and authenticate await imap.connect() console.log("Connected to IMAP server") // Select inbox const metadata = await imap.selectFolder("INBOX") console.log(`Inbox has ${metadata.emails} emails, ${metadata.recent} recent`) // Search for unread emails const unreadIds = await imap.searchEmails({ seen: false }) console.log(`Found ${unreadIds.length} unread emails`) if (unreadIds.length === 0) { return new Response(JSON.stringify({ status: "success", unreadCount: 0 }), { headers: { "Content-Type": "application/json" } }) } // Fetch unread emails without marking as read const emails = await imap.fetchEmails({ folder: "INBOX", limit: [Math.min(...unreadIds), Math.max(...unreadIds)], fetchBody: false, // Only fetch headers for efficiency peek: true }) // Process emails const processed = emails.map(email => ({ id: email.messageID, from: email.from, subject: email.subject, date: email.date.toISOString(), contentType: email.contentType })) // Return results return new Response(JSON.stringify({ status: "success", unreadCount: processed.length, emails: processed }, null, 2), { headers: { "Content-Type": "application/json" } }) } catch (error) { console.error("IMAP error:", error) return new Response(JSON.stringify({ status: "error", message: error.message, cause: error.cause }), { status: 500, headers: { "Content-Type": "application/json" } }) } finally { // Always logout to close connection try { await imap.logout() console.log("Disconnected from IMAP server") } catch (logoutError) { console.error("Logout error:", logoutError) } } } } ``` -------------------------------- ### Search Emails by Criteria using IMAP Source: https://context7.com/exerra/cf-imap/llms.txt Searches for emails within an IMAP folder based on various criteria such as 'seen' status, sender, subject, size, date range, or simply all emails. It returns an array of email IDs that match the search criteria. These IDs can then be used with the `fetchEmails` function for further processing. ```typescript export default { async fetch(request: Request): Promise { try { await imap.connect() await imap.selectFolder("INBOX") // Search for unseen emails from specific sender const unseenIds = await imap.searchEmails({ seen: false, from: "important@example.com" }) // Search for emails with subject containing text const subjectIds = await imap.searchEmails({ subject: "Invoice" }) // Search for large, recent emails const recentLargeIds = await imap.searchEmails({ recent: true, largerThan: 100000 // bytes }) // Search emails from date range const dateRangeIds = await imap.searchEmails({ since: new Date("2024-01-01"), before: new Date("2024-12-31") }) // Get all email IDs const allIds = await imap.searchEmails({ all: true }) return new Response(JSON.stringify({ unseen: unseenIds, withSubject: subjectIds, recentLarge: recentLargeIds, dateRange: dateRangeIds, all: allIds }, null, 2), { headers: { "Content-Type": "application/json" } }) } catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }) } finally { await imap.logout() } } } ``` -------------------------------- ### Select IMAP Folder with CF-Imap Source: https://context7.com/exerra/cf-imap/llms.txt Selects a specific IMAP folder for subsequent operations and returns metadata about it, including email counts and available flags. This function is essential for performing actions on a particular folder. The connection is logged out in the finally block. ```typescript export default { async fetch(request: Request): Promise { try { await imap.connect() const metadata = await imap.selectFolder("INBOX") // Returns: { // emails: 42, // recent: 5, // flags: ["Answered", "Flagged", "Deleted", "Seen", "Draft"], // permanentFlags: ["Answered", "Flagged", "Deleted", "Seen", "Draft"], // uidvalidity: 1234567890, // uidnext: 43 // } return new Response(JSON.stringify(metadata, null, 2), { headers: { "Content-Type": "application/json" } }) } catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }) } finally { await imap.logout() } } } ``` -------------------------------- ### Logout and Close IMAP Connection (TypeScript) Source: https://context7.com/exerra/cf-imap/llms.txt Properly terminates the IMAP session and closes the underlying socket connection. This function connects to the IMAP server, performs operations (indicated by a comment), and then calls the 'logout' method. It is crucial for releasing server resources and should be called at the end of any IMAP interaction. Returns a success message or an error. ```typescript export default { async fetch(request: Request): Promise { try { await imap.connect() // ... perform operations ... const loggedOut = await imap.logout() // Returns true on success return new Response("Session closed successfully") } catch (error) { return new Response(`Error: ${error.message}`, { status: 500 }) } } } ``` -------------------------------- ### Logout from IMAP Session Source: https://github.com/exerra/cf-imap/blob/main/README.md Logs out of the current IMAP session and closes the underlying socket connection. It is recommended to call this function to prevent unnecessary Worker execution and potential connection issues with some IMAP providers. ```typescript await imap.logout() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.