### Complete Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md A comprehensive example demonstrating initialization of APIs, creating a contact, and sending a transactional email. ```typescript import { TransactionalEmailsApi, TransactionalEmailsApiApiKeys, ContactsApi, ContactsApiApiKeys, HttpError } from '@getbrevo/brevo'; async function main() { // Initialize APIs const emailApi = new TransactionalEmailsApi(); emailApi.setApiKey(TransactionalEmailsApiApiKeys.apiKey, process.env.BREVO_API_KEY); const contactsApi = new ContactsApi(); contactsApi.setApiKey(ContactsApiApiKeys.apiKey, process.env.BREVO_API_KEY); try { // Create a contact console.log('Creating contact...'); const contactResponse = await contactsApi.createContact({ email: 'user@example.com', attributes: { FIRSTNAME: 'John' }, listIds: [1] }); console.log('Contact created:', contactResponse.body.id); // Send welcome email console.log('Sending email...'); const emailResponse = await emailApi.sendTransacEmail({ sender: { email: 'noreply@company.com' }, to: [{ email: 'user@example.com' }], subject: 'Welcome!', htmlContent: '

Welcome to our service!

' }); console.log('Email sent:', emailResponse.body.messageId); console.log('✓ Completed successfully'); } catch (error) { if (error instanceof HttpError) { console.error(`✗ Error ${error.statusCode}: ${error.body?.message}`); } else { console.error('✗ Unexpected error:', error); } } } main(); ``` -------------------------------- ### Loading Environment Variables Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Example of loading environment variables using the 'dotenv' package. ```typescript import dotenv from 'dotenv'; dotenv.config(); const apiKey = process.env.BREVO_API_KEY; if (!apiKey) { throw new Error('BREVO_API_KEY environment variable is required'); } ``` -------------------------------- ### Complete Setup Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/configuration.md Example demonstrating complete setup including API initialization, custom headers, and interceptors. ```typescript import { ContactsApi, ContactsApiApiKeys, TransactionalEmailsApi, TransactionalEmailsApiApiKeys, HttpError } from '@getbrevo/brevo'; // Initialize APIs const contactsApi = new ContactsApi(); contactsApi.setApiKey(ContactsApiApiKeys.apiKey, process.env.BREVO_API_KEY); const emailApi = new TransactionalEmailsApi(); emailApi.setApiKey(TransactionalEmailsApiApiKeys.apiKey, process.env.BREVO_API_KEY); // Optional: Add custom headers contactsApi.defaultHeaders = { 'X-App-Version': '1.0.0' }; // Optional: Add interceptor for logging contactsApi.addInterceptor((options) => { console.log(`[${new Date().toISOString()}] ${options.method} ${options.url}`); return Promise.resolve(); }); // Usage with error handling async function main() { try { const response = await contactsApi.getContacts(10, 0); console.log('Contacts:', response.body.contacts); } catch (error) { if (error instanceof HttpError) { console.error(`Error: ${error.statusCode} - ${error.body?.message}`); } else { console.error('Unexpected error:', error); } } } main(); ``` -------------------------------- ### Handle Webhook Events Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Example of how to set up an Express.js server to receive and process webhook events from Brevo. ```typescript import express from 'express'; const app = express(); app.use(express.json()); app.post('/webhooks/brevo', (req, res) => { const event = req.body; console.log(`Event: ${event.type} for ${event.email}`); // Process event based on type switch (event.type) { case 'sent': console.log('Email sent'); break; case 'delivered': console.log('Email delivered'); break; case 'opened': console.log('Email opened'); break; case 'clicked': console.log(`Link clicked: ${event.link}`); break; case 'bounced': console.log(`Bounce: ${event.bounceType}`); break; } res.status(200).json({ success: true }); }); ``` -------------------------------- ### Get Lists Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Retrieve a paginated list of all contact lists. ```typescript const response = await contactsApi.getLists(10, 0); console.log('Lists:', response.body.lists); ``` -------------------------------- ### Create List Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Create a new contact list. ```typescript const response = await contactsApi.createList({ name: 'Newsletter Subscribers', folderId: 1 }); console.log('List ID:', response.body.id); ``` -------------------------------- ### Get Deals Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Retrieves a list of CRM deals, with options for offset and limit to paginate results. ```typescript const response = await dealsApi.crmDealsGet( undefined, undefined, undefined, 0, // offset 20 // limit ); console.log('Deals:', response.body.deals); ``` -------------------------------- ### Initialize SDK Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Initialize the TransactionalEmailsApi and set your API key. ```typescript import { TransactionalEmailsApi, TransactionalEmailsApiApiKeys } from '@getbrevo/brevo'; const emailApi = new TransactionalEmailsApi(); emailApi.setApiKey(TransactionalEmailsApiApiKeys.apiKey, process.env.BREVO_API_KEY); ``` -------------------------------- ### Create Contact Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Create a new contact with their email, attributes, and list subscriptions. ```typescript import { ContactsApi, ContactsApiApiKeys } from '@getbrevo/brevo'; const contactsApi = new ContactsApi(); contactsApi.setApiKey(ContactsApiApiKeys.apiKey, process.env.BREVO_API_KEY); const response = await contactsApi.createContact({ email: 'new.user@example.com', attributes: { FIRSTNAME: 'John', LASTNAME: 'Doe', COMPANY: 'ACME Corp' }, listIds: [1, 2], updateEnabled: true // Update if already exists }); console.log('Contact ID:', response.body.id); ``` -------------------------------- ### Get Account Info Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Retrieves account information, including details about the current plan and remaining credits for emails and SMS, as well as the plan expiration date. ```typescript import { AccountApi, AccountApiApiKeys } from '@getbrevo/brevo'; const accountApi = new AccountApi(); accountApi.setApiKey(AccountApiApiKeys.apiKey, process.env.BREVO_API_KEY); const response = await accountApi.getAccount(); console.log('Email Credits:', response.body.plan.credits); console.log('SMS Credits:', response.body.plan.smsCredits); console.log('Plan Expires:', response.body.plan.endDate); ``` -------------------------------- ### Send Campaign Now Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Sends a previously created email campaign immediately. ```typescript await campaignsApi.sendEmailCampaignNow(campaignId); ``` -------------------------------- ### Get Campaign Stats Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Retrieves the global statistics for a specific email campaign, including opens and clicks. ```typescript const response = await campaignsApi.getEmailCampaign( campaignId, 'globalStats' ); console.log('Opens:', response.body.stats.globalStats.opens); console.log('Clicks:', response.body.stats.globalStats.clicks); ``` -------------------------------- ### Send Simple Email Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Send a transactional email with basic details. ```typescript const response = await emailApi.sendTransacEmail({ sender: { email: 'noreply@company.com', name: 'Company' }, to: [{ email: 'user@example.com' }], subject: 'Hello', htmlContent: '

Welcome!

', textContent: 'Welcome!' }); console.log('Sent:', response.body.messageId); ``` -------------------------------- ### Complete Contact Workflow Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/ContactsApi.md An example demonstrating a complete contact workflow, including creating, updating, retrieving, adding to a list, and getting campaign statistics for a contact. ```typescript import { ContactsApi, ContactsApiApiKeys, CreateContact, UpdateContact } from '@getbrevo/brevo'; const contactsApi = new ContactsApi(); contactsApi.setApiKey(ContactsApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); try { // Create a new contact const createResponse = await contactsApi.createContact({ email: 'new.user@example.com', extId: 'user-12345', attributes: { FIRSTNAME: 'Jane', LASTNAME: 'Smith', COMPANY: 'Tech Corp' }, listIds: [1, 2], updateEnabled: true, }); console.log('Contact created with ID:', createResponse.body.id); // Update the contact await contactsApi.updateContact('new.user@example.com', { attributes: { FIRSTNAME: 'Janet', PHONE: '+1234567890' } }); // Get contact details const infoResponse = await contactsApi.getContactInfo('new.user@example.com'); console.log('Contact info:', infoResponse.body); // Add to another list await contactsApi.addContactToList(3, { emails: ['new.user@example.com'] }); // Get campaign statistics const statsResponse = await contactsApi.getContactStats('new.user@example.com'); console.log('Campaign stats:', statsResponse.body); } catch (error) { console.error('Contact operation failed:', error.body?.message); } ``` -------------------------------- ### Create Email Campaign Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Demonstrates how to create a new email campaign with specified name, subject, content, sender, recipients, schedule, and tags. ```typescript import { EmailCampaignsApi, EmailCampaignsApiApiKeys } from '@getbrevo/brevo'; const campaignsApi = new EmailCampaignsApi(); campaignsApi.setApiKey(EmailCampaignsApiApiKeys.apiKey, process.env.BREVO_API_KEY); const response = await campaignsApi.createEmailCampaign({ name: 'Spring Sale 2024', subject: 'Don\'t Miss Our Spring Sale!', htmlContent: '

Spring Sale

50% off everything

', sender: { email: 'marketing@company.com', name: 'Marketing' }, recipients: { listIds: [1, 2], exclusionListIds: [5] }, scheduledAt: '2024-03-21T09:00:00Z', tags: ['spring', 'sale'] }); console.log('Campaign ID:', response.body.id); ``` -------------------------------- ### Get Deals Source: https://github.com/getbrevo/brevo-node/blob/main/README.md Example of retrieving deals using the Deals API. ```typescript import { DealsApi, DealsApiApiKeys } from '@getbrevo/brevo^3.0.1'; const dealsApi = new DealsApi(); dealsApi.setApiKey(DealsApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); async function getDeals() { try { const response = await dealsApi.crmDealsGet() console.log('Deals info:', response.body); } catch (error) { console.error('Failed to get account info:', error); } } getDeals(); ``` -------------------------------- ### Get Email Campaigns Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/CampaignsAndMessagingApis.md Example of how to list email campaigns with filters. ```typescript const response = await emailCampaignsApi.getEmailCampaigns( 'classic', 'sent', 'globalStats', '2024-01-01', '2024-12-31', 50 ); console.log('Campaigns:', response.body.campaigns); console.log('Campaign count:', response.body.count); ``` -------------------------------- ### Installation Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/README.md Command to install the Brevo Node.js SDK using npm. ```bash npm install @getbrevo/brevo^3.0.1 ``` -------------------------------- ### Batch Update Contacts Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Update multiple contacts in a single request. ```typescript await contactsApi.updateBatchContacts({ contacts: [ { email: 'user1@example.com', attributes: { FIRSTNAME: 'Jane' } }, { email: 'user2@example.com', attributes: { FIRSTNAME: 'John' } } ] }); ``` -------------------------------- ### Create Deal Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Creates a new deal in the CRM with details such as title, description, value, currency, probability, stage, and expected close date. ```typescript import { DealsApi, DealsApiApiKeys } from '@getbrevo/brevo'; const dealsApi = new DealsApi(); dealsApi.setApiKey(DealsApiApiKeys.apiKey, process.env.BREVO_API_KEY); const response = await dealsApi.crmDealsPost({ title: 'Enterprise License - ACME Corp', description: 'Annual renewal', value: 50000, currency: 'USD', probability: 75, stage: 'Negotiation', closedDate: '2024-06-30' }); console.log('Deal ID:', response.body.id); ``` -------------------------------- ### Create Task Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Creates a new task in the CRM with a name, description, due date, and status. ```typescript import { TasksApi, TasksApiApiKeys } from '@getbrevo/brevo'; const tasksApi = new TasksApi(); tasksApi.setApiKey(TasksApiApiKeys.apiKey, process.env.BREVO_API_KEY); const response = await tasksApi.crmTasksPost({ name: 'Follow up with ACME Corp', description: 'Send proposal', dueDate: '2024-02-15', status: 'todo' }); console.log('Task ID:', response.body.id); ``` -------------------------------- ### Update Contact Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Update an existing contact's attributes. ```typescript await contactsApi.updateContact('john@example.com', { attributes: { FIRSTNAME: 'Jonathan', PHONE: '+1234567890' } }); ``` -------------------------------- ### Sender Management Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/WebhooksAndSendersApis.md This example shows how to create, list, get details of, validate, and update senders using the Senders API. ```typescript import { SendersApi, SendersApiApiKeys } from '@getbrevo/brevo'; const sendersApi = new SendersApi(); sendersApi.setApiKey(SendersApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); async function manageSenders() { try { // Create a new sender const createResponse = await sendersApi.createSender({ fromName: 'Alerts', fromEmail: 'alerts@company.com', replyToName: 'Support', replyToEmail: 'support@company.com' }); const senderId = createResponse.body.id; console.log('Sender created:', senderId); // List all senders const listResponse = await sendersApi.getSenders(); console.log('Available senders:'); listResponse.body.senders.forEach(sender => { console.log(` ${sender.id}: ${sender.fromEmail} - Validated: ${sender.validated}`); }); // Get sender details const detailResponse = await sendersApi.getSender(senderId); console.log('Sender details:', detailResponse.body); // Validate sender email await sendersApi.validateSenderEmail(senderId); console.log('Validation email sent'); // Update sender await sendersApi.updateSender(senderId, { replyToEmail: 'newemail@company.com' }); console.log('Sender updated'); return senderId; } catch (error) { console.error('Sender operation failed:', error.body?.message); } } await manageSenders(); ``` -------------------------------- ### Initialize API Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/README.md Example of initializing an API client and setting the API key. ```typescript import { ContactsApi, ContactsApiApiKeys } from '@getbrevo/brevo'; const api = new ContactsApi(); api.setApiKey(ContactsApiApiKeys.apiKey, process.env.BREVO_API_KEY); ``` -------------------------------- ### Send Email with Template Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Send a transactional email using a pre-defined template and parameters. ```typescript const response = await emailApi.sendTransacEmail({ sender: { email: 'noreply@company.com' }, to: [{ email: 'user@example.com' }], templateId: 123, params: { FIRSTNAME: 'John', LASTNAME: 'Doe' } }); ``` -------------------------------- ### Get Specific Email Campaign Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/CampaignsAndMessagingApis.md Example of how to retrieve a specific email campaign and its statistics. ```typescript const response = await emailCampaignsApi.getEmailCampaign(123, 'globalStats'); console.log('Opens:', response.body.stats.globalStats.opens); console.log('Clicks:', response.body.stats.globalStats.clicks); ``` -------------------------------- ### Add Contacts to List Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Add one or more contacts to a specific list by their email addresses. ```typescript await contactsApi.addContactToList(1, { emails: ['user1@example.com', 'user2@example.com'] }); ``` -------------------------------- ### Authentication Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/OVERVIEW.md Demonstrates how to instantiate an API class and set the API key for authentication. ```typescript import { TransactionalEmailsApi, TransactionalEmailsApiApiKeys } from '@getbrevo/brevo'; const emailApi = new TransactionalEmailsApi(); emailApi.setApiKey(TransactionalEmailsApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); ``` -------------------------------- ### Send Email with Attachments Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Send a transactional email with attachments, either via URL or content. ```typescript const response = await emailApi.sendTransacEmail({ sender: { email: 'noreply@company.com' }, to: [{ email: 'user@example.com' }], subject: 'Invoice', htmlContent: '

Please see attached

', attachment: [ { url: 'https://example.com/invoice.pdf', name: 'invoice.pdf' }, { content: Buffer.from('file content').toString('base64'), name: 'document.txt' } ] }); ``` -------------------------------- ### Pagination Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/types.md Example demonstrating how to use limit and offset for pagination in list endpoints. ```typescript // Get 50 items, skip first 100 await api.getItems(50, 100); ``` -------------------------------- ### Get Account Information Source: https://github.com/getbrevo/brevo-node/blob/main/README.md Example of retrieving account information using the Account API. ```typescript import { AccountApi, AccountApiApiKeys } from '@getbrevo/brevo^3.0.1'; const accountApi = new AccountApi(); accountApi.setApiKey(AccountApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); async function getAccount() { try { const response = await accountApi.getAccount(); console.log('Account info:', response.body); } catch (error) { console.error('Failed to get account info:', error); } } getAccount(); ``` -------------------------------- ### Install Brevo Node.js SDK Source: https://github.com/getbrevo/brevo-node/blob/main/README.md Install the Brevo Node.js SDK using npm. ```bash npm i @getbrevo/brevo^3.0.1 --save ``` -------------------------------- ### Create Webhook Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Creates a new webhook to receive real-time event notifications from Brevo, specifying the URL, type, and events to subscribe to. ```typescript import { WebhooksApi, WebhooksApiApiKeys } from '@getbrevo/brevo'; const webhooksApi = new WebhooksApi(); webhooksApi.setApiKey(WebhooksApiApiKeys.apiKey, process.env.BREVO_API_KEY); const response = await webhooksApi.createWebhook({ url: 'https://myapp.com/webhooks/brevo', type: 'transactional', events: ['sent', 'delivered', 'opened', 'clicked', 'bounced'] }); console.log('Webhook ID:', response.body.id); ``` -------------------------------- ### List Contacts Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Retrieve a paginated list of contacts, with options for sorting and filtering by list. ```typescript const response = await contactsApi.getContacts( 20, // limit 0, // offset undefined, undefined, 'desc', // sort: asc/desc undefined, [1, 2] // listIds filter ); console.log('Contacts:', response.body.contacts); ``` -------------------------------- ### Loading Environment Variables with dotenv Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/configuration.md Example of loading environment variables using the `dotenv` library and configuring the SDK. ```typescript import dotenv from 'dotenv'; import { ContactsApi, ContactsApiApiKeys } from '@getbrevo/brevo'; dotenv.config(); const contactsApi = new ContactsApi(process.env.BREVO_API_BASE_PATH); contactsApi.setApiKey(ContactsApiApiKeys.apiKey, process.env.BREVO_API_KEY); ``` -------------------------------- ### Check Credits Before Sending Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Checks if there are sufficient email credits available before attempting to send an email. ```typescript const account = (await accountApi.getAccount()).body; if (account.plan.credits > 0) { // Safe to send email const result = await emailApi.sendTransacEmail({...}); } else { console.log('No credits available'); } ``` -------------------------------- ### Error Handling Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Demonstrates how to catch and handle specific HttpError types returned by the Brevo API. ```typescript import { HttpError } from '@getbrevo/brevo'; try { await contactsApi.getContacts(); } catch (error) { if (error instanceof HttpError) { if (error.statusCode === 401) { console.log('Invalid API key'); } else if (error.statusCode === 402) { console.log('Insufficient credits'); } else if (error.statusCode === 404) { console.log('Resource not found'); } else if (error.statusCode === 429) { console.log('Rate limited - retry later'); } else if (error.statusCode >= 500) { console.log('Server error - retry later'); } else { console.log(`Error ${error.statusCode}: ${error.body?.message}`); } } else { console.error('Unexpected error:', error); } } ``` -------------------------------- ### Get Contacts Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/ContactsApi.md List all contacts with optional filtering and pagination. ```typescript const response = await contactsApi.getContacts( 20, 0, '2024-01-01T00:00:00Z', undefined, 'desc', undefined, [1, 2] ); console.log('Contacts:', response.body.contacts); ``` -------------------------------- ### Multi-Channel Campaign Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/CampaignsAndMessagingApis.md Example demonstrating how to create an email campaign and send a transactional SMS using Brevo's Node.js SDK. ```typescript import { EmailCampaignsApi, EmailCampaignsApiApiKeys, TransactionalSMSApi, TransactionalSMSApiApiKeys } from '@getbrevo/brevo'; const emailApi = new EmailCampaignsApi(); emailApi.setApiKey(EmailCampaignsApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); const smsApi = new TransactionalSMSApi(); smsApi.setApiKey(TransactionalSMSApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); async function sendPromotionalCampaign() { try { // Create email campaign const emailResponse = await emailApi.createEmailCampaign({ name: 'Black Friday Promotion', subject: 'Limited Time: 50% Off Everything!', htmlContent: '

Black Friday Sale

Get 50% off on all products

Shop Now ', recipients: { listIds: [1, 2] }, sender: { name: 'Sales', email: 'sales@company.com' }, scheduledAt: '2024-11-24T08:00:00Z', tags: ['black-friday', 'sale'], utmCampaign: 'black_friday_2024' }); console.log('Email campaign created:', emailResponse.body.id); // Send transactional SMS to VIP customers const smsResponse = await smsApi.sendTransacSms({ sender: 'ShopCo', recipient: '+33612345678', content: 'Exclusive: 50% off just for you! Code: VIP50', type: 'marketing', tag: 'black-friday' }); console.log('SMS sent:', smsResponse.body.messageId); // Schedule email campaign await emailApi.updateCampaignStatus(emailResponse.body.id, { status: 'scheduled' }); console.log('Campaign scheduled'); return emailResponse.body.id; } catch (error) { console.error('Campaign failed:', error.body?.message); throw error; } } await sendPromotionalCampaign(); ``` -------------------------------- ### Multiple Authentication Methods Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/configuration.md Example demonstrating how to set different authentication types like API key and partner key for APIs that support them. ```typescript const api = new ContactsApi(); api.setApiKey(ContactsApiApiKeys.apiKey, 'xkeysib-API_KEY'); // OR api.setApiKey(ContactsApiApiKeys.partnerKey, 'xkeysib-PARTNER_KEY'); ``` -------------------------------- ### List Campaigns Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Fetches a list of email campaigns, allowing filtering by type (classic or trigger) and status (draft, sent, queued, etc.), and includes global stats. ```typescript const response = await campaignsApi.getEmailCampaigns( 'classic', // type: classic or trigger 'sent', // status: draft, sent, queued, etc. 'globalStats' ); console.log('Campaigns:', response.body.campaigns); ``` -------------------------------- ### Send Scheduled Email Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Schedule a transactional email to be sent at a specific future time. ```typescript const scheduleDate = new Date(); scheduleDate.setHours(scheduleDate.getHours() + 2); const response = await emailApi.sendTransacEmail({ sender: { email: 'noreply@company.com' }, to: [{ email: 'user@example.com' }], subject: 'Scheduled Email', htmlContent: '

Coming in 2 hours

', scheduledAt: scheduleDate }); ``` -------------------------------- ### Example: Get Webhooks Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/WebhooksAndSendersApis.md Retrieves and logs details of marketing webhooks, sorted in ascending order. ```typescript const response = await webhooksApi.getWebhooks('marketing', 'asc'); response.body.webhooks.forEach(webhook => { console.log(`${webhook.id}: ${webhook.url} (${webhook.events.join(', ')})`); }); ``` -------------------------------- ### Get Deals Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/CRMApis.md Lists all deals with optional filtering and pagination. ```typescript const response = await dealsApi.crmDealsGet( undefined, undefined, undefined, 0, 20, 'desc', 'closedDate' ); console.log('Deals:', response.body.deals); ``` -------------------------------- ### Environment Variables: Setting API Key Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/configuration.md Example of implementing environment variable support for the API key. ```typescript import { ContactsApi, ContactsApiApiKeys } from '@getbrevo/brevo'; const apiKey = process.env.BREVO_API_KEY; if (!apiKey) { throw new Error('BREVO_API_KEY environment variable is required'); } const contactsApi = new ContactsApi(); contactsApi.setApiKey(ContactsApiApiKeys.apiKey, apiKey); ``` -------------------------------- ### Get Contacts Source: https://github.com/getbrevo/brevo-node/blob/main/README.md Example of retrieving contacts with limit and offset using the Contacts API. ```typescript import { ContactsApi, ContactsApiApiKeys } from '@getbrevo/brevo^3.0.1'; const contactsApi = new ContactsApi(); contactsApi.setApiKey(ContactsApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); async function getContacts(limit: number, offset: number) { try { const result = await contactsApi.getContacts(limit, offset); console.log('Contacts:', result.body); } catch (error) { console.error('Failed to get contacts:', error); } } getContacts(10, 0); // Example: get first 10 contacts ``` -------------------------------- ### Base Path Configuration Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/OVERVIEW.md Illustrates how to configure the base path for API requests, either during instantiation or by modifying the basePath property. ```typescript const api = new ContactsApi('https://custom.brevo.com/v3'); // Or api.basePath = 'https://custom.brevo.com/v3'; ``` -------------------------------- ### Create Email Campaign Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/CampaignsAndMessagingApis.md Example of how to create a new email campaign using the EmailCampaignsApi. ```typescript const response = await emailCampaignsApi.createEmailCampaign({ name: 'Spring Sale 2024', subject: 'Special Spring Offer - 30% Off!', htmlContent: '

Spring Sale

Save 30% on all products

', recipients: { listIds: [1, 2], exclusionListIds: [5] }, sender: { name: 'Marketing', email: 'marketing@company.com' }, replyTo: 'support@company.com', scheduledAt: '2024-03-21T09:00:00Z', tags: ['spring', 'sale'], utmCampaign: 'spring_2024', utmSource: 'email' }); console.log('Campaign created:', response.body.id); ``` -------------------------------- ### Example: Create Webhook Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/WebhooksAndSendersApis.md Demonstrates how to create a new webhook with specified URL, type, and events. ```typescript const response = await webhooksApi.createWebhook({ url: 'https://myapp.com/webhooks/brevo', type: 'marketing', events: ['sent', 'opened', 'clicked', 'unsubscribed'] }); console.log('Webhook ID:', response.body.id); ``` -------------------------------- ### Instantiate API with your credentials (v3.0.0+) Source: https://github.com/getbrevo/brevo-node/blob/main/README.md Example of how to instantiate the Contacts API and set API key for versions 3.0.0 and above. ```typescript let contactAPI = new ContactsApi(); (contactAPI as any).authentications.apiKey.apiKey = "xkeysib-xxxxxxxxx"; ``` -------------------------------- ### Example: Get Webhook Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/WebhooksAndSendersApis.md Fetches and logs details of a specific webhook, including its events and creation date. ```typescript const response = await webhooksApi.getWebhook(123); console.log('Webhook:', response.body); console.log('Events:', response.body.events); console.log('Created:', response.body.createdAt); ``` -------------------------------- ### Make API Call Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/README.md Example of making a basic API call to get contacts and accessing the typed response body. ```typescript const response = await api.getContacts(10, 0); console.log(response.body.contacts); // Access typed response ``` -------------------------------- ### 404 Not Found Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/errors.md Example of catching a 404 Not Found error when trying to retrieve a resource. ```typescript try { const template = await emailApi.getSmtpTemplate(999999); } catch (error) { if (error instanceof HttpError && error.statusCode === 404) { if (error.body?.code === 'document_not_found') { console.log('Template not found'); } } } ``` -------------------------------- ### Batch Send Emails Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Send a transactional email to multiple recipients, with personalized content using params. ```typescript const response = await emailApi.sendTransacEmail({ sender: { email: 'noreply@company.com' }, to: [ { email: 'user1@example.com', name: 'User 1' }, { email: 'user2@example.com', name: 'User 2' }, { email: 'user3@example.com', name: 'User 3' } ], subject: 'Batch Email', htmlContent: '

Hello {{FIRSTNAME}}

', params: { FIRSTNAME: 'valued customer' }, tags: ['batch', 'campaign'] }); ``` -------------------------------- ### Instantiate API with your credentials (Pre v3.0.0) Source: https://github.com/getbrevo/brevo-node/blob/main/README.md Example of how to instantiate the Contacts API and set API key for older versions. ```typescript let contactAPI = new ContactsApi(); (contactAPI as any).authentications.apiKey.apiKey = "xkeysib-xxxxxxxxx" ``` -------------------------------- ### createAttribute Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/ContactsApi.md Example of creating a new contact attribute. ```typescript await contactsApi.createAttribute( 'normal', 'CUSTOM_FIELD', { type: 'text', enumeration: [] } ); ``` -------------------------------- ### Build your contact (v3.0.0+) Source: https://github.com/getbrevo/brevo-node/blob/main/README.md Example of how to build a contact object for versions 3.0.0 and above. ```typescript let contact = new CreateContact(); contact.email = "michael.brown@example.com"; contact.attributes = { FIRSTNAME: { value: "Michael" }, LASTNAME: { value: "Brown" } }; ``` -------------------------------- ### Webhook Integration Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/WebhooksAndSendersApis.md This example demonstrates how to create, list, and update webhooks, and how to handle incoming webhook events in an Express.js application. ```typescript import { WebhooksApi, WebhooksApiApiKeys } from '@getbrevo/brevo'; import express from 'express'; const webhooksApi = new WebhooksApi(); webhooksApi.setApiKey(WebhooksApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); // Create webhook endpoint async function setupWebhooks() { try { const response = await webhooksApi.createWebhook({ url: 'https://myapp.com/webhooks/brevo', type: 'transactional', events: ['sent', 'delivered', 'opened', 'clicked', 'bounced', 'complained'] }); console.log('Webhook created:', response.body.id); return response.body.id; } catch (error) { console.error('Failed to create webhook:', error.body?.message); } } // Express webhook handler const app = express(); app.post('/webhooks/brevo', express.json(), (req, res) => { const event = req.body; // Handle different event types switch (event.type) { case 'sent': console.log(`Email sent to ${event.email} (messageId: ${event.messageId})`); break; case 'delivered': console.log(`Email delivered to ${event.email}`); break; case 'opened': console.log(`Email opened by ${event.email} at ${event.ts}`); break; case 'clicked': console.log(`Link clicked in email: ${event.link}`); break; case 'bounced': console.log(`Email bounced: ${event.email} (reason: ${event.bounceType})`); break; case 'complained': console.log(`Spam complaint from ${event.email}`); break; case 'unsubscribed': console.log(`${event.email} unsubscribed`); break; } res.status(200).json({ success: true }); }); // List all webhooks async function listWebhooks() { try { const response = await webhooksApi.getWebhooks(); console.log('Configured webhooks:'); response.body.webhooks.forEach(webhook => { console.log(` ${webhook.id}: ${webhook.url}`); console.log(` Events: ${webhook.events.join(', ')}`); console.log(` Created: ${webhook.createdAt}`); }); } catch (error) { console.error('Failed to list webhooks:', error.body?.message); } } // Update webhook async function updateWebhookEvents(webhookId, newEvents) { try { await webhooksApi.updateWebhook(webhookId, { events: newEvents }); console.log('Webhook updated'); } catch (error) { console.error('Failed to update webhook:', error.body?.message); } } app.listen(3000, async () => { await setupWebhooks(); await listWebhooks(); }); ``` -------------------------------- ### Build your contact (Pre v3.0.0) Source: https://github.com/getbrevo/brevo-node/blob/main/README.md Example of how to build a contact object for older versions. ```typescript let contact = new CreateContact(); contact.email = "michael.brown@example.com"; contact.attributes = { FIRSTNAME: { value: "Michael" }, LASTNAME: { value: "Brown" }, }; ``` -------------------------------- ### Custom Attributes Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/types.md Shows how to pass custom attributes as plain objects. ```typescript attributes: { FIRSTNAME: 'John', LASTNAME: 'Doe', COMPANY: 'ACME', CUSTOM_FIELD: 'value' } ``` -------------------------------- ### Create Deal Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/CRMApis.md Creates a new deal with specified details. ```typescript const response = await dealsApi.crmDealsPost({ title: 'Enterprise License Deal', description: 'ABC Corp enterprise license renewal', value: 50000, currency: 'USD', probability: 75, stage: 'Negotiation', closedDate: '2024-06-30', linkedContactsIds: [123] }); console.log('Deal created:', response.body.id); ``` -------------------------------- ### Create Contact Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/ContactsApi.md Create a new contact or update an existing one. ```typescript const response = await contactsApi.createContact({ email: 'john@example.com', extId: 'user123', attributes: { FIRSTNAME: 'John', LASTNAME: 'Doe', COMPANY: 'ACME' }, listIds: [2, 3], updateEnabled: true, }); console.log('Contact ID:', response.body.id); ``` -------------------------------- ### Account Monitoring Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/AccountApi.md This example demonstrates how to retrieve account details, check credit availability, monitor plan expiration, and log account information. It also shows how to fetch and display recent account activity. ```typescript import { AccountApi, AccountApiApiKeys } from '@getbrevo/brevo'; const accountApi = new AccountApi(); accountApi.setApiKey(AccountApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); async function checkAccountHealth() { try { // Get account details const accountResponse = await accountApi.getAccount(); const account = accountResponse.body; // Check credit availability if (account.plan.credits < 100) { console.warn('Warning: Less than 100 email credits remaining'); } if (account.plan.smsCredits < 50) { console.warn('Warning: Less than 50 SMS credits remaining'); } // Check plan expiration const planEndDate = new Date(account.plan.endDate); const today = new Date(); const daysUntilExpiry = Math.ceil( (planEndDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24) ); if (daysUntilExpiry < 30) { console.warn(`Plan expires in ${daysUntilExpiry} days`); } // Log account info console.log(`Account: ${account.email}`); console.log(`Company: ${account.companyName}`); console.log(`Plan: ${account.plan.type}`); console.log(`Credits: ${account.plan.credits}`); console.log(`SMS Credits: ${account.plan.smsCredits}`); console.log(`Expires: ${account.plan.endDate}`); return account; } catch (error) { console.error('Failed to get account info:', error.body?.message); throw error; } } async function viewRecentActivity(days = 30) { try { const startDate = new Date(); startDate.setDate(startDate.getDate() - days); const response = await accountApi.getAccountActivity( startDate.toISOString().split('T')[0], new Date().toISOString().split('T')[0], 100, 0 ); console.log(`Account activity (last ${days} days):`); console.log(`Total events: ${response.body.totalCount}`); response.body.events.forEach(event => { console.log(` ${event.eventDate}: ${event.eventName}`); }); return response.body.events; } catch (error) { console.error('Failed to get account activity:', error.body?.message); throw error; } } // Usage await checkAccountHealth(); await viewRecentActivity(30); ``` -------------------------------- ### updateBatchContacts Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/ContactsApi.md Example of updating multiple contacts in a single request. ```typescript await contactsApi.updateBatchContacts({ contacts: [ { email: 'john@example.com', attributes: { FIRSTNAME: 'John' } }, { email: 'jane@example.com', attributes: { FIRSTNAME: 'Jane' } } ] }); ``` -------------------------------- ### Complete CRM Workflow Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/CRMApis.md Demonstrates a full CRM workflow including creating a company, a deal, a task, adding a note, updating the deal, and retrieving deal information. ```typescript import { DealsApi, DealsApiApiKeys, CompaniesApi, CompaniesApiApiKeys, TasksApi, TasksApiApiKeys, NotesApi, NotesApiApiKeys } from '@getbrevo/brevo'; const dealsApi = new DealsApi(); dealsApi.setApiKey(DealsApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); const companiesApi = new CompaniesApi(); companiesApi.setApiKey(CompaniesApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); const tasksApi = new TasksApi(); tasksApi.setApiKey(TasksApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); const notesApi = new NotesApi(); notesApi.setApiKey(NotesApiApiKeys.apiKey, 'xkeysib-YOUR_API_KEY'); async function manageSalesOpportunity() { try { // Create a company const companyResponse = await companiesApi.crmCompaniesPost({ name: 'TechCorp Inc', description: 'Leading software company', attributes: { INDUSTRY: 'Software', EMPLOYEE_COUNT: 500 } }); const companyId = companyResponse.body.id; console.log('Company created:', companyId); // Create a deal for the company const dealResponse = await dealsApi.crmDealsPost({ title: 'Enterprise License - TechCorp', description: 'Annual enterprise software license', value: 100000, currency: 'USD', probability: 60, stage: 'Qualification', closedDate: '2024-06-30', linkedCompanyIds: [companyId] }); const dealId = dealResponse.body.id; console.log('Deal created:', dealId); // Create a follow-up task const taskResponse = await tasksApi.crmTasksPost({ name: 'Follow up with TechCorp - Send proposal', description: 'Contact TechCorp with detailed proposal', dueDate: '2024-02-15', status: 'todo', linkedDealsIds: [dealId], linkedCompanyIds: [companyId] }); console.log('Task created:', taskResponse.body.id); // Add a note to the deal const noteResponse = await notesApi.crmNotesPost({ text: 'Initial contact positive. Decision maker is CFO. Waiting for budget approval.', linkedDealsIds: [dealId], linkedCompanyIds: [companyId] }); console.log('Note added:', noteResponse.body.id); // Update the deal await dealsApi.crmDealsIdPatch(dealId, { value: 120000, probability: 75, stage: 'Proposal' }); // Retrieve updated deal const dealInfo = await dealsApi.crmDealsIdGet(dealId); console.log('Updated deal:', dealInfo.body); return { companyId, dealId, taskId: taskResponse.body.id, noteId: noteResponse.body.id }; } catch (error) { console.error('CRM operation failed:', error.body?.message); throw error; } } await manageSalesOpportunity(); ``` -------------------------------- ### blockNewDomain Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/TransactionalEmailsApi.md Example of blocking a new domain. ```typescript await emailApi.blockNewDomain({ domain: 'spam.com' }); ``` -------------------------------- ### Get SMS Report Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/QUICK_START.md Retrieves a report for transactional SMS messages within a specified date range, with optional filtering by tag. ```typescript const response = await smsApi.getTransacSmsReport( '2024-01-01', '2024-12-31', undefined, 'verification' // tag filter ); console.log('Report:', response.body); ``` -------------------------------- ### Error Handling Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/OVERVIEW.md Shows how to catch and handle HttpError exceptions from API method calls. ```typescript import { HttpError } from '@getbrevo/brevo'; try { await contactsApi.getContacts(); } catch (error) { if (error instanceof HttpError) { console.error('HTTP Error:', error.statusCode, error.body?.message); } } ``` -------------------------------- ### 422 Unprocessable Entity Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/errors.md Example of catching a 422 Unprocessable Entity error and handling specific business logic errors. ```typescript try { await emailApi.updateEmailCampaign(campaignId, updates); } catch (error) { if (error instanceof HttpError && error.statusCode === 422) { if (error.body?.code === 'campaign_sent') { console.log('Cannot update sent campaign'); } else if (error.body?.code === 'campaign_processing') { console.log('Campaign is being processed, retry later'); } } } ``` -------------------------------- ### Date Filters Example Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/types.md Illustrates the ISO 8601 format for date filters. ```typescript // YYYY-MM-DD or ISO 8601 full timestamp startDate: '2024-01-01' startDate: '2024-01-01T09:00:00Z' ``` -------------------------------- ### Export Activity Log Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/AccountApi.md This example demonstrates how to fetch account activity logs for a specified date range and format them as CSV. ```typescript const startDate = '2024-01-01'; const endDate = '2024-01-31'; const response = await accountApi.getAccountActivity(startDate, endDate, 500, 0); const csv = response.body.events .map(e => `${e.eventDate},${e.eventName}`) .join('\n'); ``` -------------------------------- ### Batch Operations Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/README.md Shows an example of updating multiple contacts in a single batch operation. ```typescript await contactsApi.updateBatchContacts({ contacts: [ { email: 'user1@example.com', attributes: { ... } }, { email: 'user2@example.com', attributes: { ... } }, ] }); ``` -------------------------------- ### Check Before Sending Email Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/api-reference/AccountApi.md A concise example to verify if there are available email credits before sending an email. ```typescript const accountResponse = await accountApi.getAccount(); if (accountResponse.body.plan.credits > 0) { // Safe to send email } ``` -------------------------------- ### Get Current Base Path Source: https://github.com/getbrevo/brevo-node/blob/main/_autodocs/configuration.md Retrieve the currently configured base path of the API client. ```javascript const api = new ContactsApi(); const currentPath = api.basePath; // Getter property console.log(currentPath); // https://api.brevo.com/v3 ```