# @getbrevo/brevo 中文文档

规范地址：https://npmcn.com/package/%40getbrevo/brevo/

版本：6\.2\.0
npm 元数据更新时间：2026-10-16T08:33:07.882Z
中文译文更新时间：2026-11-16T05:51:55.607Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40getbrevo/brevo
原文对照：https://npmcn.com/package/%40getbrevo/brevo/?lang=original
项目主页：https://github.com/getbrevo/brevo-node#readme
源码仓库：https://github.com/getbrevo/brevo-node

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：5.7 MB，3467 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.0\.0
- 运行依赖：0 个
- 首次发布：2023-06-13T19:25:31.716Z
- 最新版本发布：2026-10-16T08:33:07.482Z
- 近 30 天下载量：1764773（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：22（近 12 个月 12 个）

## 中文简介

Brevo SDK为有TypeScript支持的节点.js.

## 安装

```sh
npm install @getbrevo/brevo
```

也可以使用：`pnpm add @getbrevo/brevo`、`yarn add @getbrevo/brevo`、`bun add @getbrevo/brevo`

## README

# 布雷沃节点.js SDK

![](https://npmcn.com/package/%40getbrevo/brevo/banner.png)

[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com/?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=https%3A%2F%2Fgithub.com%2Fmourraille%2Fdemo-ts) ![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg) [![npm version](https://img.shields.io/npm/v/@getbrevo/brevo)](https://www.npmjs.com/package/@getbrevo/brevo) [![npm downloads](https://img.shields.io/npm/dm/@getbrevo/brevo)](https://www.npmjs.com/package/@getbrevo/brevo)

[网站](https://brevo.com/) 二. 支助 [API 参考](https://developers.brevo.com/) 二. 支助 [支助](mailto:support@brevo.com)

* * *

## 安装

```bash
npm install @getbrevo/brevo
```

## 快速启动

```typescript
import { BrevoClient } from '@getbrevo/brevo';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
});

const result = await brevo.transactionalEmails.sendTransacEmail({
  subject: "Hello",
  textContent: "Hello world!",
  sender: { name: "Sender", email: "sender@example.com" },
  to: [{ email: "recipient@example.com" }]
});

console.log('Email sent:', result);
```

* * *

## 配置

```typescript
const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  timeoutInSeconds: 30,
  maxRetries: 3,
});
```

### 构造选项

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `apiKey` | `string` | `null` | 你的Brevo API密钥。 见 [认证](https://npmcn.com/package/%40getbrevo/brevo/#readme-authentication)。 。 。 . |
| `clientId` | `string` | `BREVO_CLIENT_ID` 环境 var | OAuth 2.0 M2M 应用程序客户端ID |
| `clientSecret` | `string` | `BREVO_CLIENT_SECRET` 环境 var | OAuth 2.0 M2M 应用程序客户端秘密 |
| `token` | `string` | `null` | 您已经拥有的 OAuth 访问令牌( 未被 SDK 刷新) |
| `auth` | `AuthProvider` | `null` | 自定义认证提供者( 动态符号, 密钥旋转) . |
| `timeoutInSeconds` | `number` | `60` | 默认请求超时( 秒) |
| `maxRetries` | `number` | `2` | 可重试错误的最大尝试 |
| `baseUrl` | `string` | `null` | 覆盖默认 API 基础 URL |
| `fetch` | `typeof fetch` | `null` | 自定义获取执行 |
| `headers` | `Record<string, string>` | `null` | 每次请求都会发送额外的默认信头 |
| `logging` | `LogConfig | Logger` | `null` | 日志配置 |

* * *

## 认证

客户端支持两种认证方法. 每个客户使用一个.

### API 密钥

```typescript
import { BrevoClient } from '@getbrevo/brevo';

const brevo = new BrevoClient({ apiKey: 'xkeysib-xxx' });
```

在您的 Brevo 账户中创建 API 密钥 [app.brevo.com/设定/钥匙/api](https://app.brevo.com/settings/keys/api)。见 [API 密钥认证](https://developers.brevo.com/docs/api-key-authentication)。 。 。 .

### OAuth 2.0 机对机(M2M)

传递M2M应用程序的客户端身份和秘密. 客户端在第一次请求时将它们交换为访问令牌,重新使用令牌,并在新令牌到期前不久取取取(令牌有效约一小时).

```typescript
import { BrevoClient } from '@getbrevo/brevo';

const brevo = new BrevoClient({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
});

const account = await brevo.account.getAccount();
```

或者设定 `BREVO_CLIENT_ID` 财务报告和审定财务报表 `BREVO_CLIENT_SECRET` 在环境中创建客户端,没有参数:

```typescript
const brevo = new BrevoClient();
```

如果您已经拥有访问符, 请直接通过 。 客户端发送它作为 - 而不是刷新它:

```typescript
const brevo = new BrevoClient({ token: 'your-access-token' });
```

客户端要求的标志包含给应用程序的每一个范围. 创建 M2M 应用程序并选择其范围,或者请求带有特定范围的信使,参见 [机器对机器(M2M)认证](https://developers.brevo.com/docs/oauth-m2m-authentication)。 。 。 .

## 处理错误

SDK基于HTTP状态代码抛出特定出错类型.

```typescript
import { Brevo, BrevoError } from '@getbrevo/brevo';

try {
  await brevo.transactionalEmails.sendTransacEmail({...});
} catch (err) {
  if (err instanceof Brevo.UnauthorizedError) {
    console.error('Invalid API key');
  } else if (err instanceof Brevo.TooManyRequestsError) {
    const retryAfter = err.rawResponse.headers['retry-after'];
    console.error(`Rate limited. Retry after ${retryAfter} seconds`);
  } else if (err instanceof BrevoError) {
    console.error(`API Error ${err.statusCode}:`, err.message);
  }
}
```

输入的子类在名称空格下 `Brevo` (例如:. `Brevo.UnauthorizedError`)——仅 `BrevoError` 财务报告和审定财务报表 `BrevoTimeoutError` 属于顶级出口.

**错误类型 :**

-   `400` - 说吧 `Brevo.BadRequestError`
-   `401` - 说吧 `Brevo.UnauthorizedError`
-   `403` - 说吧 `Brevo.ForbiddenError`
-   `404` - 说吧 `Brevo.NotFoundError`
-   `422` - 说吧 `Brevo.UnprocessableEntityError`
-   `429` - 说吧 `Brevo.TooManyRequestsError`
-   `500+` - 说吧 `Brevo.InternalServerError`

错误属性

全体 `BrevoError` 实例提供:

-   `statusCode`: HTTP 状态代码
-   `message`: 错误消息
-   `body`: 解析出错反应正文
-   `rawResponse`: 有信头的原始响应

* * *

## 检索

默认情况下启用了带有指数后退的自动重试(2个重试).

```typescript
// Client-level
const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  maxRetries: 3
});

// Request-level
await brevo.transactionalEmails.sendTransacEmail({...}, {
  maxRetries: 5
});
```

**可重试状态代码 :** `408`, (中文(简体) ), `429`, (中文(简体) ), `500`, (中文(简体) ), `502`, (中文(简体) ), `503`, (中文(简体) ), `504`

复试如何工作

-   指向后退:~1s,~2s,~4s(带有焦急)
-   尊重 `Retry-After` 费率限制页眉
-   可禁用每个请求 `maxRetries: 0`

* * *

## 超时

默认超时为60秒. 在客户端或请求级别配置 .

```typescript
// Client-level
const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  timeoutInSeconds: 30
});

// Request-level
await brevo.transactionalEmails.sendTransacEmail({...}, {
  timeoutInSeconds: 10
});
```

**建议值:**

-   标准 API 呼叫 : `30-60s` (默认)
-   快速行动: `10-15s`
-   散装操作 : `120-300s`
-   实时 : `5-10s`

* * *

## 请求选项

### 其他信头

```typescript
await brevo.transactionalEmails.sendTransacEmail({...}, {
  headers: {
    'X-Custom-Header': 'custom-value'
  }
});
```

### 查询参数

```typescript
await brevo.transactionalEmails.sendTransacEmail({...}, {
  queryParams: {
    'customParam': 'value'
  }
});
```

### 中止信号

```typescript
const controller = new AbortController();
await brevo.transactionalEmails.sendTransacEmail({...}, {
  abortSignal: controller.signal
});
controller.abort();
```

### 原始反应

```typescript
const { data, rawResponse } = await brevo.transactionalEmails.sendTransacEmail({...})
  .withRawResponse();

console.log(rawResponse.headers['X-My-Header']);
```

* * *

## 二进制响应

```typescript
const response = await brevo.inboundParsing.getInboundEmailAttachment(...);

// Choose one:
const stream = response.stream();
// const arrayBuffer = await response.arrayBuffer();
// const blob = await response.blob();
// const bytes = await response.bytes();
```

保存到文件示例

**节点.js(可读结构):**

```typescript
import { createWriteStream } from 'fs';
import { Readable } from 'stream';
import { pipeline } from 'stream/promises';

const stream = response.stream();
const nodeStream = Readable.fromWeb(stream);
await pipeline(nodeStream, createWriteStream('path/to/file'));
```

**宾:**

```typescript
await Bun.write('path/to/file', response.stream());
```

**浏览器 :**

```typescript
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'filename';
a.click();
URL.revokeObjectURL(url);
```

* * *

## 类型脚本

所有请求和响应类型均被导出.

```typescript
import { BrevoClient } from '@getbrevo/brevo';

const request: Brevo.SendTransacEmailRequest = {
  subject: "First email",
  textContent: "Hello world!",
  sender: { name: "Bob Wilson", email: "bob.wilson@example.com" },
  to: [{ email: "sarah.davis@example.com", name: "Sarah Davis" }]
};
```

* * *

## 日志

```typescript
import { BrevoClient, logging } from '@getbrevo/brevo';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  logging: {
    level: logging.LogLevel.Debug,
    logger: new logging.ConsoleLogger(),
    silent: false
  }
});
```

自定义日志示例

```typescript
import winston from 'winston';

const winstonLogger = winston.createLogger({...});

const logger: logging.ILogger = {
  debug: (msg, ...args) => winstonLogger.debug(msg, ...args),
  info: (msg, ...args) => winstonLogger.info(msg, ...args),
  warn: (msg, ...args) => winstonLogger.warn(msg, ...args),
  error: (msg, ...args) => winstonLogger.error(msg, ...args),
};
```

* * *

## 自定义获取客户端

覆盖默认获取高级使用案例的执行 .

```typescript
const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  fetch: async (url, options) => {
    console.log('→', url);
    const response = await fetch(url, options);
    console.log('←', response.status);
    return response;
  },
});
```

常用案例

**使用节点比对 :**

```typescript
import fetch from 'node-fetch';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  fetch: fetch as typeof globalThis.fetch,
});
```

**使用undici :**

```typescript
import { fetch } from 'undici';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  fetch: fetch as typeof globalThis.fetch,
});
```

**使用请求的ID头 :**

```typescript
import { randomUUID } from 'crypto';

const brevo = new BrevoClient({
  apiKey: 'your-api-key',
  fetch: async (url, options) => {
    return fetch(url, {
      ...options,
      headers: {
        ...options?.headers,
        'X-Request-ID': randomUUID(),
      },
    });
  },
});
```

* * *

## 运行时间相容性

-   节点.js 18+
-   维塞尔
-   云花岗工人
-   德诺v1.25+
-   1.0+号舱
-   原生反应

* * *

## 从v5.x升级

v6是主要发布. 大部分突破性变化来自在Brevo的内部努力,使终点、参数和模型更加完善 **自我描述** ——所以名称,形状和需要的字段传达意向而不需要交叉引用外部的docs(既用于开发者,也用于对Brevo API工作的AI代理).

v5.x 继续支持. 如果你需要暂时坚持v5, 把它贴上:

```bash
npm install @getbrevo/brevo@^5.0
```

查看 v5 – v6 迁移指南

### 中断更改

**公司 - `getCompanies` 过滤参数重命名**

```typescript
// v5
await brevo.companies.getCompanies({ filters: 'foo' });

// v6
await brevo.companies.getCompanies({ 'filters[attributes.name]': 'foo' });
```

旧的 `filters` 名称仍然在编译,但过滤器是静默地丢弃的服务器侧并获得未过滤的列表。 审计每个呼叫网站.

**事件—— `createBatchEvents` 有效载外形**

```typescript
// v5
await brevo.event.createBatchEvents([{ /* event */ }]);

// v6
await brevo.event.createBatchEvents({ events: [{ /* event */ }] });
```

**余额 -- -- `getActiveBalancesApi` 响应参数重命名( t)**

-   已替换响应类型 : `BalanceLimit` → `GetLoyaltyBalanceProgramsPidActiveBalanceResponse`。 。 。 .
-   参数从蛇 case更名为骆驼Case: `contact_id` → `contactId`, (中文(简体) ), `balance_definition_id` → `balanceDefinitionId`, (中文(简体) ), `sort_field` → `sortField`。 。 。 .

**余额 -- -- `getContactBalances` 需求 `balanceDefinitionId`**

**客户关系管理 - `getCrmTasktypes` 返回数组** (单位:千美元)`GetCrmTasktypesResponseItem[]`) (中文(简体) ).

**模式字段已删除**数字 : `GetWebhook.channel`, (中文(简体) ), `GetProcessResponseInfo.export`, (中文(简体) ), `GetEventsList.events[].source`, (中文(简体) ), `GetExtendedCampaignOverview.utmIDActive` (替换为: `utmID: number`) (中文(简体) ).

**模型字段重命名**数字 : `ConversationsMessage.File.filename` → `name`, (中文(简体) ), `.url` → `link`· ; `SendTransacSms.tag` 现在 `string | string[]`。 。 。 .

**现在需要的字段**数字 : `GetContactDetails.whatsappBlacklisted`, (中文(简体) ), `Note.text`, (中文(简体) ), `Task.date`。 。 。 .

### 已添加

-   `BrevoClient` 接受一个新的 `auth` 自定义选项 `AuthProvider` 注射(现有) `apiKey` 继续工作.
-   新建可选字段和过滤器 `contacts.createContact`, (中文(简体) ), `contacts.updateContact`, (中文(简体) ), `emailCampaigns.getEmailCampaigns`, (中文(简体) ), `ecommerce.getProducts`,以及若干其他终点.

* * *

## 从 v3.x 迁移

查看迁移指南

**v3.x: (中文(简体) )**

```typescript
import { TransactionalEmailsApi, SendSmtpEmail } from "@getbrevo/brevo";

let emailAPI = new TransactionalEmailsApi();
(emailAPI as any).authentications.apiKey.apiKey = "xkeysib-xxx";

let message = new SendSmtpEmail();
message.subject = "First email";
message.textContent = "Hello world!";
message.sender = { name: "Bob Wilson", email: "bob.wilson@example.com" };
message.to = [{ email: "sarah.davis@example.com", name: "Sarah Davis" }];

emailAPI.sendTransacEmail(message);
```

**v6.x: (中文(简体) )**

```typescript
import { BrevoClient } from '@getbrevo/brevo';

const brevo = new BrevoClient({
  apiKey: 'xkeysib-xxx',
});

await brevo.transactionalEmails.sendTransacEmail({
  subject: "First email",
  textContent: "Hello world!",
  sender: { name: "Bob Wilson", email: "bob.wilson@example.com" },
  to: [{ email: "sarah.davis@example.com", name: "Sarah Davis" }],
});
```

> \[尖叫声\] 遗产 v3.x SDK (中文(简体) )`@getbrevo/brevo@^3.0.1`将继续收到重要的安保最新情况,但没有新的特征。 我们建议迁移到v6.x.

* * *

## 捐款

这个图书馆是按程序创建的。 直接对图书馆作出的修改将覆盖。 请先打开一个问题讨论修改事宜 .

总是欢迎为这一研究提供捐款!

* * *

## 支助

-   [API 参考](https://developers.brevo.com/)
-   [GitHub 问题](https://github.com/getbrevo/brevo-node/tree/main)
-   [电子邮件支持](mailto:support@brevo.com)

## 常见问题

### @getbrevo/brevo 是什么？

Brevo SDK为有TypeScript支持的节点\.js\.

### 如何安装 @getbrevo/brevo？

在项目目录运行 npm install @getbrevo/brevo，或使用 pnpm add / yarn add / bun add。

### @getbrevo/brevo 支持 TypeScript 吗？

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

### @getbrevo/brevo 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @getbrevo/brevo 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @getbrevo/brevo 可以商用吗？

@getbrevo/brevo 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @getbrevo/brevo 的下载量有多少？

根据 npm 官方下载统计，@getbrevo/brevo 在 2026/10/17 – 2026/11/15 这 30 天内被下载 1,764,773 次，日均约 58,826 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @getbrevo/brevo 还在维护吗？

最新版本 6\.2\.0 发布于 2026/10/16（30 天前）；至今共发布 22 个版本，其中过去 12 个月发布了 12 个；首次发布于 2023/06/14。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

