npm package: @gera2ld/imap
Description: A lightweight IMAP client for Node.js that supports real-time email monitoring using IDLE mode.
Latest version: 0.0.1

# IMAP Client

A lightweight IMAP client for Node.js that supports real-time email monitoring using IDLE mode.

## Usage

### Basic Example

```typescript
import { ImapClient } from '@gera2ld/imap';

const client = new ImapClient({
  host: 'imap.example.com',
  port: 993,
  secure: true,
  user: 'your-email@example.com',
  password: 'your-password',
});

// Connect and authenticate
await client.connect();

// Select a mailbox
await client.selectMailbox('INBOX');

// Perform operations like fetching messages
const messages = await client.fetchMessages('1:*', ['UID', 'ENVELOPE']);
console.log(messages);

// Disconnect
await client.disconnect();
```

### Watching for New Mails and Deletions Using IDLE Mode

```typescript
import { ImapClient } from '@gera2ld/imap';

async function watchEmails() {
  const client = new ImapClient({
    host: 'imap.example.com',
    port: 993,
    secure: true,
    user: 'your-email@example.com',
    password: 'your-password',
  });

  try {
    // Connect and authenticate
    await client.connect();
    
    // Select the mailbox to watch (e.g., INBOX)
    await client.selectMailbox('INBOX');
    
    // Listen for new emails
    client.on('newmail', (info) => {
      console.log(`New mail received! Total messages in mailbox: ${info.count}`);
      // Handle new email notification
    });
    
    // Listen for message deletions
    client.on('expunge', (info) => {
      console.log(`Message deleted! Sequence number: ${info.seq}`);
      // Handle message deletion
    });
    
    // Listen for other changes
    client.on('fetch', (message) => {
      console.log(`Message ${message.seq} updated with attributes:`, message.attributes);
    });
    
    // Start listening for real-time updates using IDLE mode
    await client.startIdle();
    console.log('Now listening for new emails and deletions...');
    
    // Keep the program running to continue listening
    // Set up graceful shutdown
    const handleShutdown = async () => {
      console.log('Shutting down gracefully...');
      try {
        // Stop listening for updates
        await client.stopIdle();
        // Disconnect from the server
        await client.disconnect();
        console.log('Disconnected from IMAP server');
        process.exit(0);
      } catch (err) {
        console.error('Error during shutdown:', err);
        process.exit(1);
      }
    };

    // Listen for termination signals
    process.on('SIGINT', handleShutdown);
    process.on('SIGTERM', handleShutdown);

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the example
watchEmails();
```

## Authentication

The client supports multiple authentication methods:

### Password Authentication
```typescript
const client = new ImapClient({
  host: 'imap.example.com',
  port: 993,
  secure: true,
  user: 'your-email@example.com',
  password: 'your-password',
});
```

### XOAUTH2 Authentication
```typescript
const client = new ImapClient({
  host: 'imap.example.com',
  port: 993,
  secure: true,
  user: 'your-email@example.com',
  accessToken: 'your-oauth-token',
});

// Or with a function that returns a token
const client = new ImapClient({
  host: 'imap.example.com',
  port: 993,
  secure: true,
  user: 'your-email@example.com',
  accessToken: async () => {
    // Return a fresh access token
    return await getFreshAccessToken();
  },
});
```

## Available Events

- `newmail`: Emitted when new messages arrive in the mailbox
- `expunge`: Emitted when messages are deleted from the mailbox
- `fetch`: Emitted when message attributes are updated
- `recent`: Emitted when the number of recent messages changes
- `flags`: Emitted when message flags change
- `list`: Emitted when mailbox list information is received
- `response`: Emitted for raw IMAP responses
- `error`: Emitted when an error occurs
- `close`: Emitted when the connection is closed

## API

### ImapClient(options)

Creates a new IMAP client instance.

#### Options

- `host` (string): The IMAP server hostname
- `port` (number): The IMAP server port (typically 143 for non-secure, 993 for secure)
- `secure` (boolean): Whether to use TLS/SSL connection
- `user` (string): The username/email address
- `password` (string, optional): The password for authentication
- `accessToken` (string | function, optional): Access token for XOAUTH2 authentication

### connect()

Connects to the IMAP server and performs authentication.

### disconnect()

Disconnects from the IMAP server and cleans up resources.

### selectMailbox(mailbox)

Selects a mailbox for subsequent operations.

### listMailboxes()

Lists all mailboxes on the server.

### fetchMessages(sequence, [items], [options])

Fetches messages from the currently selected mailbox.
- `items` (optional): The message data items to fetch (e.g., ['UID', 'ENVELOPE', 'BODY.PEEK[]']). Defaults to ['UID', 'ENVELOPE', 'FLAGS']
- `options` (optional): Additional options for the fetch operation
  - `uid` (boolean, default: true): Whether to use UID-based fetch

### searchMessages(criteria, [options])

Searches messages in the currently selected mailbox based on the given criteria.
- `options` (optional): Additional options for the search operation
  - `uid` (boolean, default: true): Whether to use UID-based search

### setFlags(sequence, operation, flags, [options])

Sets flags on messages in the currently selected mailbox.
- `operation`: The flag operation ('+' to add flags, '-' to remove flags, '=' to replace all flags)
- `flags`: Array of flags to operate on (e.g., ['\\Seen', '\\Flagged'])
- `options` (optional): Additional options for the operation
  - `uid` (boolean, default: true): Whether to use UID-based operation

### markAsSeen(sequence, [options])

Marks messages as seen in the currently selected mailbox.
- `options` (optional): Additional options for the operation
  - `uid` (boolean, default: true): Whether to use UID-based operation

### markAsUnseen(sequence, [options])

Marks messages as unseen in the currently selected mailbox.
- `options` (optional): Additional options for the operation
  - `uid` (boolean, default: true): Whether to use UID-based operation

### deleteMessages(sequence, [options])

Deletes messages in the currently selected mailbox.
- `options` (optional): Additional options for the operation
  - `uid` (boolean, default: true): Whether to use UID-based operation

### moveMessages(sequence, destinationMailbox, [options])

Moves messages to a different mailbox.
- `options` (optional): Additional options for the operation
  - `uid` (boolean, default: true): Whether to use UID-based operation

### startIdle()

Manually starts IDLE mode for real-time updates.

### stopIdle()

Manually stops IDLE mode.

## Utilities

The package also exports utility functions for working with IMAP:

### formatDateForImap(date)

Formats a Date object to the IMAP date format used in SEARCH commands (e.g., SINCE, ON).
The format is "DD-MMM-YYYY" (e.g., "01-Jan-2023").

```typescript
import { formatDateForImap } from '@gera2ld/imap';

const date = new Date('2023-01-15');
const imapDate = formatDateForImap(date); // "15-Jan-2023"

// Use in search commands
await client.searchMessages(`SINCE ${imapDate}`);
```

### formatDateTimeForImap(date)

Formats a Date object to the IMAP datetime format used in SEARCH commands.
The format is "DD-MMM-YYYY HH:MM:SS +ZZZZ" (e.g., "01-Jan-2023 12:00:00 +0000").

```typescript
import { formatDateTimeForImap } from '@gera2ld/imap';

const date = new Date('2023-01-15T14:30:00Z');
const imapDateTime = formatDateTimeForImap(date); // "15-Jan-2023 14:30:00 +0000"
```

## License

MIT