BrevoApiClient 1.0.1

dotnet add package BrevoApiClient --version 1.0.1
                    
NuGet\Install-Package BrevoApiClient -Version 1.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BrevoApiClient" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BrevoApiClient" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="BrevoApiClient" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BrevoApiClient --version 1.0.1
                    
#r "nuget: BrevoApiClient, 1.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BrevoApiClient@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BrevoApiClient&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=BrevoApiClient&version=1.0.1
                    
Install as a Cake Tool

BrevoApiClient

NuGet Version NuGet Downloads Build Status License: MIT

A comprehensive, enterprise-grade .NET client library for the Brevo API (formerly SendinBlue). Built with modern C# practices, SOLID principles, and extensive error handling.

🚀 Features

  • Complete API Coverage: All Brevo API endpoints supported
  • Email Campaigns: Create, manage, send, and track email campaigns
  • SMS Campaigns: Full SMS campaign functionality
  • Transactional Messaging: Send transactional emails and SMS
  • Contact Management: Comprehensive contact and list management
  • External Feeds: Integration with external data feeds
  • Enterprise-Grade: Built-in error handling, logging, and retry mechanisms
  • Modern C#: Async/await throughout, nullable reference types, latest C# features
  • Dependency Injection: Ready-to-use with Microsoft.Extensions.DependencyInjection
  • Modern .NET: Built for .NET 8.0
  • Well-Tested: Over 3600+ unit tests ensuring reliability
  • Strong Typing: Comprehensive models for all API responses

📦 Installation

dotnet add package BrevoApiClient

Or via Package Manager Console:

Install-Package BrevoApiClient

⚡ Quick Start

1. Configuration

{
  "Brevo": {
    "ApiKey": "your-brevo-api-key-here",
    "BaseUrl": "https://api.brevo.com/v3/",
    "TimeoutSeconds": 30
  }
}
Using Dependency Injection
using BrevoApiClient.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add Brevo API Client
builder.Services.AddBrevoApiClient(builder.Configuration);

var app = builder.Build();
Manual Configuration
using BrevoApiClient.Extensions;
using BrevoApiClient.Configuration;

var services = new ServiceCollection();

services.AddBrevoApiClient(options =>
{
    options.ApiKey = "your-brevo-api-key-here";
    options.BaseUrl = "https://api.brevo.com/v3/";
    options.TimeoutSeconds = 30;
});

var serviceProvider = services.BuildServiceProvider();

2. Basic Usage

using BrevoApiClient.Interfaces;

public class EmailService
{
    private readonly IEmailCampaignsService _emailCampaigns;
    private readonly ITransactionalEmailsService _transactionalEmails;
    private readonly IContactsService _contacts;

    public EmailService(
        IEmailCampaignsService emailCampaigns,
        ITransactionalEmailsService transactionalEmails,
        IContactsService contacts)
    {
        _emailCampaigns = emailCampaigns;
        _transactionalEmails = transactionalEmails;
        _contacts = contacts;
    }

    public async Task SendWelcomeEmailAsync(string email, string name)
    {
        // Send a transactional email
        var request = new SendTransactionalEmailRequest
        {
            To = new[] { new TransactionalEmailRecipient { Email = email, Name = name } },
            Subject = "Welcome to our service!",
            HtmlContent = $"<h1>Welcome {name}!</h1><p>Thanks for joining us.</p>",
            Sender = new EmailSender { Name = "Your Company", Email = "noreply@yourcompany.com" }
        };

        var response = await _transactionalEmails.SendTransactionalEmailAsync(request);
        Console.WriteLine($"Email sent with ID: {response.MessageId}");
    }
}

📖 Comprehensive Examples

Email Campaigns

Creating an Email Campaign
public async Task CreateEmailCampaignAsync()
{
    var request = new CreateEmailCampaignRequest
    {
        Name = "Monthly Newsletter",
        Subject = "Our Latest Updates",
        HtmlContent = "<html><body><h1>Newsletter</h1><p>Hello {{contact.FIRSTNAME}},</p></body></html>",
        Sender = new EmailCampaignSender
        {
            Name = "Your Company",
            Email = "newsletter@yourcompany.com"
        },
        Recipients = new EmailCampaignRecipients
        {
            ListIds = new[] { 1, 2, 3 } // Your contact lists
        },
        ScheduledAt = DateTime.UtcNow.AddHours(2) // Schedule for later
    };

    var response = await _emailCampaigns.CreateEmailCampaignAsync(request);
    Console.WriteLine($"Campaign created with ID: {response.Id}");
}
Sending a Campaign Immediately
public async Task SendCampaignNowAsync(long campaignId)
{
    await _emailCampaigns.SendEmailCampaignNowAsync(campaignId);
    Console.WriteLine("Campaign sent successfully!");
}
Getting Campaign Statistics
public async Task GetCampaignStatsAsync(long campaignId)
{
    var campaign = await _emailCampaigns.GetEmailCampaignAsync(campaignId);
    
    Console.WriteLine($"Campaign: {campaign.Name}");
    Console.WriteLine($"Sent: {campaign.Statistics?.Sent}");
    Console.WriteLine($"Opens: {campaign.Statistics?.UniqueOpens}");
    Console.WriteLine($"Clicks: {campaign.Statistics?.UniqueClicks}");
    Console.WriteLine($"Bounces: {campaign.Statistics?.HardBounces + campaign.Statistics?.SoftBounces}");
}

Contact Management

Creating a Contact
public async Task CreateContactAsync()
{
    var request = new CreateContactRequest
    {
        Email = "john.doe@example.com",
        Attributes = new Dictionary<string, object>
        {
            ["FIRSTNAME"] = "John",
            ["LASTNAME"] = "Doe",
            ["SMS"] = "+1234567890"
        },
        ListIds = new[] { 1, 2 }, // Add to specific lists
        UpdateEnabled = true // Update if contact already exists
    };

    var response = await _contacts.CreateContactAsync(request);
    Console.WriteLine($"Contact created with ID: {response.Id}");
}
Updating a Contact
public async Task UpdateContactAsync(string email)
{
    var request = new UpdateContactRequest
    {
        Attributes = new Dictionary<string, object>
        {
            ["FIRSTNAME"] = "Jane",
            ["LASTNAME"] = "Smith",
            ["COMPANY"] = "Tech Corp"
        },
        ListIds = new[] { 3, 4 }, // Move to different lists
        UnlinkListIds = new[] { 1 } // Remove from list 1
    };

    await _contacts.UpdateContactAsync(email, request);
    Console.WriteLine("Contact updated successfully!");
}
Searching Contacts
public async Task SearchContactsAsync()
{
    var response = await _contacts.GetContactsAsync(
        limit: 50,
        offset: 0,
        modifiedSince: DateTime.UtcNow.AddDays(-7), // Last 7 days
        sort: "desc"
    );

    Console.WriteLine($"Found {response.Count} contacts");
    foreach (var contact in response.Contacts)
    {
        Console.WriteLine($"- {contact.Email} ({contact.Attributes?["FIRSTNAME"]} {contact.Attributes?["LASTNAME"]})");
    }
}

Transactional Emails

Sending with Templates
public async Task SendTemplateEmailAsync()
{
    var request = new SendTransactionalEmailRequest
    {
        TemplateId = 123, // Your template ID
        To = new[]
        {
            new TransactionalEmailRecipient
            {
                Email = "customer@example.com",
                Name = "Customer Name"
            }
        },
        Params = new Dictionary<string, object>
        {
            ["CUSTOMER_NAME"] = "John Doe",
            ["ORDER_ID"] = "ORD-12345",
            ["TOTAL_AMOUNT"] = "$99.99"
        },
        Tags = new[] { "order-confirmation", "transactional" }
    };

    var response = await _transactionalEmails.SendTransactionalEmailAsync(request);
    Console.WriteLine($"Email queued with ID: {response.MessageId}");
}
Sending with Attachments
public async Task SendEmailWithAttachmentAsync()
{
    var request = new SendTransactionalEmailRequest
    {
        To = new[] { new TransactionalEmailRecipient { Email = "customer@example.com" } },
        Subject = "Invoice #12345",
        HtmlContent = "<p>Please find your invoice attached.</p>",
        Sender = new EmailSender { Name = "Billing", Email = "billing@yourcompany.com" },
        Attachment = new[]
        {
            new EmailAttachment
            {
                Name = "invoice-12345.pdf",
                Content = Convert.ToBase64String(File.ReadAllBytes("invoice.pdf"))
            }
        }
    };

    await _transactionalEmails.SendTransactionalEmailAsync(request);
}

SMS Campaigns

Creating and Sending SMS
public async Task SendSmsAsync()
{
    var request = new CreateSmsCampaignRequest
    {
        Name = "Promotion Alert",
        Sender = "YourBrand",
        Content = "🎉 Special offer! Get 20% off with code SAVE20. Valid until midnight!",
        Recipients = new SmsCampaignRecipients
        {
            ListIds = new[] { 5, 6 } // SMS contact lists
        },
        ScheduledAt = DateTime.UtcNow.AddMinutes(30)
    };

    var response = await _smsCampaigns.CreateSmsCampaignAsync(request);
    
    // Send immediately if needed
    await _smsCampaigns.SendSmsCampaignNowAsync(response.Id);
}

Error Handling

The client provides comprehensive error handling with custom exceptions:

public async Task HandleErrorsAsync()
{
    try
    {
        await _contacts.GetContactAsync("nonexistent@example.com");
    }
    catch (BrevoNotFoundException ex)
    {
        Console.WriteLine($"Contact not found: {ex.Message}");
    }
    catch (BrevoValidationException ex)
    {
        Console.WriteLine($"Validation errors:");
        foreach (var error in ex.ValidationErrors)
        {
            Console.WriteLine($"- {error}");
        }
    }
    catch (BrevoRateLimitException ex)
    {
        Console.WriteLine($"Rate limited. Retry after: {ex.RetryAfter}");
    }
    catch (BrevoAuthenticationException ex)
    {
        Console.WriteLine($"Authentication failed: {ex.Message}");
    }
    catch (BrevoApiException ex)
    {
        Console.WriteLine($"API Error: {ex.Message} (Status: {ex.StatusCode})");
    }
}

Advanced Configuration

Custom HTTP Configuration
services.AddBrevoApiClient(options =>
{
    options.ApiKey = "your-api-key";
    options.BaseUrl = "https://api.brevo.com/v3/";
    options.TimeoutSeconds = 60;
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
    Proxy = new WebProxy("http://proxy:8080")
});
Custom Logging
public class MyService
{
    private readonly IEmailCampaignsService _emailService;
    private readonly ILogger<MyService> _logger;

    public MyService(IEmailCampaignsService emailService, ILogger<MyService> logger)
    {
        _emailService = emailService;
        _logger = logger;
    }

    public async Task ProcessCampaignAsync()
    {
        try
        {
            _logger.LogInformation("Starting campaign creation");
            // The Brevo client will automatically log API calls
            var response = await _emailService.CreateEmailCampaignAsync(request);
            _logger.LogInformation("Campaign created successfully: {CampaignId}", response.Id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create campaign");
        }
    }
}

🔧 Available Services

Service Description
IAccountService Account information and user management
IEmailCampaignsService Email campaign creation, management, and analytics
ISmsCampaignsService SMS campaign functionality
ITransactionalEmailsService Send transactional emails and templates
ITransactionalSmsService Send transactional SMS messages
IContactsService Contact and list management
IExternalFeedsService External data feeds integration
IConversationsService Conversations and messaging
IEcommerceService E-commerce tracking and integration
IWebhooksService Webhook management
IDealsService CRM deals management
ICompaniesService Company management
ITasksService Task management
INotesService Notes management
IPaymentsService Payment processing
IFilesService File management
IDomainsService Domain authentication
ISendersService Sender management

🛠️ Development

Building the Project

git clone https://github.com/DevNines/BrevoApiClient.git
cd BrevoApiClient
dotnet restore
dotnet build

Running Tests

dotnet test

The project includes over 3600+ comprehensive unit tests covering all endpoints and scenarios.

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass (dotnet test)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🤝 Support

📈 Changelog

v1.0.0

  • 🎉 Initial release
  • ✅ Complete Brevo API coverage
  • ✅ Enterprise-grade error handling
  • ✅ Comprehensive logging
  • ✅ Dependency injection support
  • ✅ Built for .NET 8.0
  • ✅ 3600+ unit tests

Made with ❤️ for the .NET community

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.1 135 8/10/2025
1.0.0 203 8/7/2025

🚀 Version 1.0.0 - Complete Brevo API Client

✅ Features:
• Complete Email Campaigns API support (create, send, manage, analytics)
• Full SMS Campaigns functionality
• Transactional Email and SMS services
• Comprehensive Contacts and Lists management
• External Feeds integration
• Account, Domains, Webhooks, and all other endpoints
• Enterprise-grade error handling with custom exceptions
• Comprehensive logging and diagnostics
• Built-in retry mechanisms and rate limiting support
• Async/await throughout with CancellationToken support
• Clean architecture with SOLID principles
• Extensive unit test coverage (3600+ tests)
• Strong typing with comprehensive models
• Dependency injection ready with IServiceCollection extensions

📦 Installation: dotnet add package BrevoApiClient
📖 Documentation: https://github.com/DevNines/BrevoApiClient#readme