@civitas-cerebrum/email-client

中文文档
0.0.10发布于 2026/11/01MITTypeScriptES Module构建来源已验证近 30 天下载 3023

A generic SMTP/IMAP email client for test automation. Send, receive, search, and clean emails with composable filters.

原始使用文档
文档目录16 节
  1. Why this client?
  2. Installation
  3. Quick Start
  4. Send-Only (SMTP)
  5. Receive-Only (IMAP)
  6. Full Client (Send + Receive)
  7. API Reference
  8. Initialization
  9. Legacy Format
  10. Sending Emails ( send )
  11. Receiving Emails ( receive / receiveAll )
  12. Managing the Inbox ( mark / clean )
  13. The ReceivedEmail Object
  14. Error Handling
  15. Contributing
  16. License

@civitas-cerebrum/email-client

NPM Version

A highly robust, zero-dependency SMTP/IMAP email client built specifically for E2E test automation. Send, receive, search, manage, and clean emails using composable, deterministic filters.

Why this client?

  • Zero Playwright runtime dependency — Works seamlessly with Playwright, Cypress, Vitest, Jest, or any Node.js test runner.
  • Smart Polling Engine — Built-in retry logic prevents flaky tests caused by slow email delivery.
  • Memory Protected — Automatically caps raw MIME fetches to prevent Node.js memory crashes when hitting large, unmanaged test inboxes.
  • Two-Phase Matching — Evaluates exact IMAP criteria first, then falls back to a smart, case-insensitive client-side match to catch poorly formatted automated emails.
  • Full Mailbox Management — Send, receive, flag, archive, and aggressively clean your test environment.

Installation

npm install @civitas-cerebrum/email-client

Quick Start

Send-Only (SMTP)

import { EmailClient } from '@civitas-cerebrum/email-client';

const client = new EmailClient({
    smtp: {
        email: '[email protected]',
        password: 'app-password',
        host: 'smtp.example.com',
    },
});

await client.send({
    to: '[email protected]',
    subject: 'Your OTP Code',
    text: 'Your code is 123456',
});

Receive-Only (IMAP)

import { EmailClient, EmailFilterType } from '@civitas-cerebrum/email-client';

const client = new EmailClient({
    imap: {
        email: '[email protected]',
        password: 'app-password',
    },
});

const email = await client.receive({
    filters: [{ type: EmailFilterType.SUBJECT, value: 'Your OTP Code' }],
});
console.log(email.text);

Full Client (Send + Receive)

SMTP and IMAP credentials are independent — they can point to different providers or accounts. For example, send via a transactional relay and receive from Gmail:

import { EmailClient, EmailFilterType, EmailMarkAction } from '@civitas-cerebrum/email-client';

const client = new EmailClient({
    smtp: {
        email: '[email protected]',
        password: 'app-password',
        host: 'smtp.example.com',
    },
    imap: {
        email: '[email protected]',
        password: 'app-password',
    },
});

await client.send({ to: '[email protected]', subject: 'OTP', text: '123456' });

const email = await client.receive({
    filters: [{ type: EmailFilterType.SUBJECT, value: 'OTP' }],
});

await client.mark({
    action: EmailMarkAction.READ,
    filters: [{ type: EmailFilterType.SUBJECT, value: 'OTP' }],
});

await client.clean({
    filters: [{ type: EmailFilterType.SUBJECT, value: 'OTP' }],
});

API Reference

Initialization

Constructor: new EmailClient({ smtp?, imap? }) or new EmailClient(legacyCredentials)

SmtpCredentials (required for send()):

FieldTypeDefaultDescription
emailstring—SMTP sender email address
passwordstring—SMTP sender password or app password
hoststring—SMTP host (e.g., 'smtp.gmail.com')
portnumber587SMTP port

ImapCredentials (required for receive(), receiveAll(), clean(), mark()):

FieldTypeDefaultDescription
emailstring—IMAP email address
passwordstring—IMAP password or app password
hoststring'imap.gmail.com'IMAP host
portnumber993IMAP port

Legacy Format

The old flat EmailCredentials interface is still supported for backward compatibility. Migration to the new split format is encouraged.

// Legacy format (still supported)
const client = new EmailClient({
    senderEmail: '[email protected]',
    senderPassword: 'app-password',
    senderSmtpHost: 'smtp.example.com',
    receiverEmail: '[email protected]',
    receiverPassword: 'app-password',
});

Sending Emails (send)

Supports plain text, inline HTML, and loading HTML files directly from disk.

// Plain text
await client.send({ to: '[email protected]', subject: 'Test', text: 'Hello' });

// Inline HTML
await client.send({ to: '[email protected]', subject: 'Report', html: '<h1>Results</h1>' });

// HTML template from disk
await client.send({ to: '[email protected]', subject: 'Report', htmlFile: 'emails/template.html' });

Receiving Emails (receive / receiveAll)

The client uses a robust polling mechanism. It will continuously query the IMAP server until the waitTimeout is reached or the filters are satisfied. Combine multiple filters to create strict AND logic constraints. When multiple emails match, receive() returns the most recent one by date.

// Get the single most recent matching email
const email = await client.receive({
    filters: [{ type: EmailFilterType.SUBJECT, value: 'Your OTP' }],
    waitTimeout: 15000 // Optional: fail if not found in 15s
});

// Get ALL matching emails in the inbox (useful for batch processing)
const allEmails = await client.receiveAll({
    filters: [
        { type: EmailFilterType.FROM, value: '[email protected]' },
        { type: EmailFilterType.SINCE, value: new Date('2025-01-01') },
    ],
});

Receive Options

OptionTypeDefaultDescription
filtersEmailFilter[]—Required. Array of filters (AND logic)
folderstring'INBOX'IMAP folder to search. Accepts a literal path or a specialUse role (e.g. '\\Sent', '\\Trash')
foldersstring[]—Several folders to search at once. Takes precedence over folder. See Searching multiple folders
waitTimeoutnumber30000Max milliseconds to poll before throwing an error
pollIntervalnumber3000Milliseconds to wait between IMAP fetch attempts
expectedCountnumber1Number of matching emails required before returning
downloadDirstringos.tmpdir()Directory to save downloaded .html copies
maxFetchLimitnumber50Max emails to fetch per polling cycle (memory protection)

Searching multiple folders

A message does not always arrive where you expect it. Mail from a new or low-reputation sending domain is routinely filed as spam by the receiving server, and a spam-filed message is never found by an inbox-only search — no matter how long you wait for it.

Pass folders to search several mailboxes in one call. Every folder is searched on every polling cycle and the matches are pooled, so the wait ends as soon as the message shows up anywhere in the set:

const email = await client.receive({
    filters: [{ type: EmailFilterType.SUBJECT, value: 'Your verification code' }],
    folders: ['INBOX', '[Gmail]/Spam'],   // or ['INBOX', '\\Junk'] to stay portable
    waitTimeout: 60000,
});

folders is accepted by receive, receiveAll, clean and mark, and takes precedence over folder when both are given. For clean and mark the action is applied in each folder in turn and the returned count is the total.

Missing folders. A single folder is strict — naming one that does not exist throws, listing the folders the server does have. A folder list is tolerant: an absent folder is skipped so a portable set works against servers that lack one of them. If none of the listed folders can be opened, the call still throws.

Do not reach for \All as a shortcut. All Mail also contains sent, archived and recently-deleted copies, so a search across it will keep finding a message you have already moved or deleted. Name the folders you actually mean.

Available Filters (EmailFilterType)

TypeValue TypeDescription
SUBJECTstringExact or partial match of the email subject
FROMstringSender email address
TOstringRecipient email address
CONTENTstringMatches anywhere in the HTML body or plain text fallback
SINCEDateOnly fetch emails received after this timestamp

Managing the Inbox (mark / clean)

Keep your automated test inboxes clean and organized to prevent IMAP throttling and memory issues.

Mark (Flagging and Moving)

Modify the state of emails matching specific criteria. Returns the number of emails affected.

// Apply standard flags
await client.mark({
    action: EmailMarkAction.READ, // READ, UNREAD, FLAGGED, UNFLAGGED
    filters: [{ type: EmailFilterType.SUBJECT, value: 'Welcome' }]
});

// Move emails to an archive folder (using specialUse role — works across all locales)
await client.mark({
    action: EmailMarkAction.ARCHIVED,
    filters: [{ type: EmailFilterType.FROM, value: '[email protected]' }],
    archiveFolder: '\\Trash' // Resolves to the server's actual Trash path at runtime
});

// Apply custom IMAP flags
await client.mark({
    action: ['\\Draft', '\\Answered'],
    filters: [{ type: EmailFilterType.SUBJECT, value: 'Custom State' }]
});

Clean (Deleting)

Permanently delete emails from the server.

// Delete specific emails
await client.clean({
    filters: [{ type: EmailFilterType.FROM, value: '[email protected]' }],
});

// Delete across several folders in one call
await client.clean({
    filters: [{ type: EmailFilterType.SUBJECT, value: 'my-test-run-42' }],
    folders: ['INBOX', '[Gmail]/Spam'],
});

// Nuke an entire folder (Use with caution!)
await client.clean();                       // every message in INBOX
await client.clean({ folder: 'scratch' });  // every message in "scratch"

Sharing a mailbox? clean() with no filters deletes everything in the target folder, including messages another process put there. If more than one test run can touch the same mailbox, stamp a unique per-run token into every subject you send and always pass a filter selecting it — then a cleanup can only ever remove its own mail. Reserve the unfiltered form for a folder your run created and owns.

Folder Resolution

Any folder or archiveFolder option accepts either a literal path (e.g. '[Gmail]/Trash') or a specialUse role prefixed with \. The client resolves roles to the correct server path at runtime using IMAP LIST metadata, so your code works regardless of the mail server's language or naming conventions.

RoleDescription
\AllAll Mail
\TrashTrash / Deleted Items
\SentSent Mail
\DraftsDrafts
\JunkSpam
\FlaggedStarred / Flagged
\InboxInbox
// These are equivalent on a Turkish Gmail account:
await client.clean({ folder: '[Gmail]/Çöp kutusu' }); // literal path
await client.clean({ folder: '\\Trash' });             // specialUse role (locale-independent)

The ReceivedEmail Object

When you receive an email, the client parses the raw MIME source and returns a clean, strongly-typed object:

PropertyTypeDescription
subjectstringEmail subject line
fromstringSender address
tostringRecipient address
dateDateDate the email was sent
htmlstringParsed HTML body (empty string if plain-text only)
textstringParsed plain-text content
filePathstringLocal path to the downloaded .html copy

Error Handling

The client provides clear error messages when credentials are missing for a specific operation:

OperationMissing CredentialsError Message
send()SMTPSMTP credentials are required to send emails. Provide { smtp: { email, password, host } } when constructing EmailClient.
receive() / receiveAll()IMAPIMAP credentials are required to receive/manage emails. Provide { imap: { email, password } } when constructing EmailClient.
clean() / mark()IMAPIMAP credentials are required to receive/manage emails. Provide { imap: { email, password } } when constructing EmailClient.

Contributing

git clone https://github.com/Umutayb/email-client.git
cd email-client
npm install
npm run test

License

MIT

版本与发布记录

@civitas-cerebrum/email-client 共发布 10 个版本,首次发布于 2026/03/23;过去 12 个月发布了 10 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.0.10latest2026/11/018 天前
0.0.92026/08/122 个月前
0.0.82026/06/194 个月前
0.0.72026/04/146 个月前
0.0.62026/03/287 个月前
0.0.52026/03/277 个月前

关于 @civitas-cerebrum/email-client 的常见问题

@civitas-cerebrum/email-client 是什么?

A generic SMTP/IMAP email client for test automation. Send, receive, search, and clean emails with composable filters.

如何安装 @civitas-cerebrum/email-client?

在项目目录运行 npm install @civitas-cerebrum/email-client,或使用 pnpm add / yarn add / bun add。

@civitas-cerebrum/email-client 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@civitas-cerebrum/email-client 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@civitas-cerebrum/email-client 可以商用吗?

@civitas-cerebrum/email-client 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@civitas-cerebrum/email-client 的下载量有多少?

根据 npm 官方下载统计,@civitas-cerebrum/email-client 在 2026/10/10 – 2026/11/08 这 30 天内被下载 3,023 次,日均约 101 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@civitas-cerebrum/email-client 还在维护吗?

最新版本 0.0.10 发布于 2026/11/01(8 天前);至今共发布 10 个版本,其中过去 12 个月发布了 10 个;首次发布于 2026/03/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。