BrevoApiClient 1.0.1
dotnet add package BrevoApiClient --version 1.0.1
NuGet\Install-Package BrevoApiClient -Version 1.0.1
<PackageReference Include="BrevoApiClient" Version="1.0.1" />
<PackageVersion Include="BrevoApiClient" Version="1.0.1" />
<PackageReference Include="BrevoApiClient" />
paket add BrevoApiClient --version 1.0.1
#r "nuget: BrevoApiClient, 1.0.1"
#:package BrevoApiClient@1.0.1
#addin nuget:?package=BrevoApiClient&version=1.0.1
#tool nuget:?package=BrevoApiClient&version=1.0.1
BrevoApiClient
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
Using appsettings.json (Recommended)
{
"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
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Make your changes
- Add tests for new functionality
- Ensure all tests pass (
dotnet test
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - 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 | Versions 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. |
-
net8.0
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.1)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 8.0.0)
- System.Text.Json (>= 8.0.5)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
🚀 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