# Brevo Email Provider

# Brevo Email Provider

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [emailsender/src/providers/brevo.ts](emailsender/src/providers/brevo.ts)

</details>



The **Brevo Email Provider** acts as the external API adapter boundary for the `EmailSender` microservice. It encapsulates the complexity of the Brevo (formerly Sendinblue) REST API, providing a clean interface for sending transactional emails and mapping external delivery events to the system's internal domain statuses.

## BrevoClient Implementation

The `BrevoClient` class is the primary integration point. It is responsible for constructing authenticated HTTP requests to the Brevo API and handling the lifecycle of an email dispatch.

### API Integration Details
The client targets the Brevo SMTP API endpoint (`/smtp/emails`) using the standard `fetch` API. It handles authentication via the `api-key` header and manages error parsing for non-2xx responses.

| Component | Description |
| :--- | :--- |
| **Endpoint** | Defaults to `https://api.brevo.com/v1` but is configurable via the constructor [emailsender/src/providers/brevo.ts:27-30](). |
| **Authentication** | Uses the `api-key` header [emailsender/src/providers/brevo.ts:39-39](). |
| **Method** | HTTP `POST` [emailsender/src/providers/brevo.ts:36-36](). |
| **Error Handling** | Attempts to parse `BrevoError` JSON; falls back to raw status text if parsing fails [emailsender/src/providers/brevo.ts:44-52](). |

### Data Flow: Email Dispatch
The following diagram illustrates the transformation and flow of data from the internal request to the Brevo API.

**Dispatch Sequence and Data Mapping**
```mermaid
sequenceDiagram
    participant S as "EmailService"
    participant B as "BrevoClient"
    participant API as "Brevo API (External)"

    S->>B: sendEmail(BrevoEmailRequest)
    Note over B: Set headers: api-key, Content-Type
    B->>API: POST /smtp/emails (JSON Body)
    alt Success (2xx)
        API-->>B: { messageId: string, messageIds?: string[] }
        B-->>S: BrevoEmailResponse
    else Error (4xx/5xx)
        API-->>B: { code: string, message: string }
        B-->>S: throw Error(`Brevo API error: ...`)
    end
```
**Sources:** [emailsender/src/providers/brevo.ts:32-60]()

## Data Structures

The provider defines specific interfaces to ensure type safety when interacting with the external API.

### Request Interface (`BrevoEmailRequest`)
The request object supports standard SMTP fields including recipients, CC/BCC, and content types.
*   **Recipients**: Arrays of objects containing `email` and optional `name` [emailsender/src/providers/brevo.ts:2-4]().
*   **Content**: Supports both `htmlContent` and `textContent` [emailsender/src/providers/brevo.ts:6-7]().
*   **Metadata**: Includes `tags` for tracking and categorization within the Brevo dashboard [emailsender/src/providers/brevo.ts:10-10]().

### Response Interface (`BrevoEmailResponse`)
The response captures the unique identifiers generated by Brevo, which are essential for tracking delivery status via webhooks.
*   `messageId`: The primary ID for the sent message [emailsender/src/providers/brevo.ts:14-14]().
*   `messageIds`: An optional array of IDs if multiple recipients were handled individually [emailsender/src/providers/brevo.ts:15-15]().

**Sources:** [emailsender/src/providers/brevo.ts:1-21]()

## Status Mapping Logic

A critical responsibility of the `BrevoClient` is the `mapStatus` function. This method translates Brevo's specific event strings (received via webhooks) into the internal status schema used by the `EmailSender` microservice to maintain consistency across different providers.

### Mapping Table

| Brevo Status (Input) | Internal Status (Output) | Description |
| :--- | :--- | :--- |
| `sent` | `sent` | Accepted by Brevo's SMTP server. |
| `delivered` | `delivered` | Successfully reached the recipient's server. |
| `opened`, `clicked` | `opened`, `clicked` | User engagement events. |
| `bounce`, `hardbounce`, `softbounce` | `bounced` | Delivery failure (permanent or temporary). |
| `spam` | `spam` | Marked as spam by recipient. |
| `blocked` | `blocked` | Recipient is on a blocklist. |
| `invalid`, `error` | `failed` | Processing or formatting error. |

**Sources:** [emailsender/src/providers/brevo.ts:62-79]()

## Integration Architecture

The `BrevoClient` serves as the implementation detail for the external adapter boundary. While the `EmailService` handles business logic (like template rendering), it relies on `BrevoClient` for the actual network transmission.

**Provider Boundary Diagram**
```mermaid
graph TD
    subgraph "EmailSender Microservice"
        A["EmailService"] -- "calls" --> B["BrevoClient.sendEmail()"]
        C["WebhookService"] -- "calls" --> D["BrevoClient.mapStatus()"]
    end

    subgraph "External"
        B -- "HTTPS POST" --> E["Brevo API"]
        F["Brevo Webhooks"] -- "HTTPS POST" --> G["/webhook endpoint"]
        G -- "routes to" --> C
    end

    style B stroke-width:2px
    style D stroke-width:2px
```

**Sources:** [emailsender/src/providers/brevo.ts:23-30](), [emailsender/src/providers/brevo.ts:62-62]()

---
