DEV Community

Abdur Rakib Rony
Abdur Rakib Rony

Posted on

Building a Professional Email System with Next.js and Brevo: A Complete Guide

In this comprehensive guide, we'll explore how to create a robust email system using Next.js and Brevo (formerly Sendinblue). We'll build professional, responsive email templates and implement a reliable email sending system.

Table of Contents

  1. Introduction
  2. Setting Up Brevo
  3. Project Setup
  4. Creating Email Templates
  5. Implementing the API
  6. Testing and Troubleshooting
  7. Best Practices
  8. Conclusion

Introduction
Email communication remains a crucial component of modern web applications. Whether it's order confirmations, password resets, or promotional content, having a reliable email system is essential. In this tutorial, we'll use Brevo's powerful email API with Next.js to create a professional email system.

Setting Up Brevo
First, you'll need to set up your Brevo account:

  1. Sign up at Brevo
  2. Navigate to SMTP & API section
  3. Generate an API key
  4. Add and verify your domain
// Store your API key in .env.local
BREVO_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

Project Setup
Let's start by installing the necessary dependencies:

npm install @sendinblue/client
Enter fullscreen mode Exit fullscreen mode

Creating Email Templates
We'll create reusable email templates using a modular approach. Here's an example structure:

// utils/emailRenderer.js
export function renderEmailTemplate(templateName, data) {
  const sharedStyles = {
    mainContainer: "font-family: Arial, sans-serif; max-width: 600px;",
    header: "text-align: center; margin-bottom: 30px;",
    // ... more shared styles
  };

  const templates = {
    orderConfirmation: ({ orderNumber, items, total }) => `
      <div style="${sharedStyles.mainContainer}">
        <!-- Template content -->
      </div>
    `,
    // ... more templates
  };

  return templates[templateName](data);
}
Enter fullscreen mode Exit fullscreen mode

Implementing the API
Create an API route to handle email sending:

// app/api/send-email/route.js
import { NextResponse } from "next/server";
import * as SibApiV3Sdk from "@sendinblue/client";
import { getEmailTemplate } from "@/utils/emailUtils";

export async function POST(req) {
  try {
    const { toEmail, subject, templateName, templateData } = await req.json();

    const htmlContent = getEmailTemplate(templateName, templateData);
    const client = new SibApiV3Sdk.TransactionalEmailsApi();

    client.setApiKey(
      SibApiV3Sdk.TransactionalEmailsApiApiKeys.apiKey,
      process.env.BREVO_API_KEY
    );

    const emailData = {
      sender: { email: "no-reply@yourdomain.com", name: "Your Brand" },
      to: [{ email: toEmail }],
      subject: subject,
      htmlContent: htmlContent,
      // ... additional configuration
    };

    const response = await client.sendTransacEmail(emailData);
    return NextResponse.json({ success: true, response });
  } catch (err) {
    console.error("Error sending email:", err);
    return NextResponse.json(
      { error: "An error occurred while sending the email" },
      { status: 500 }
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Testing Your Email System
Here's an example of how to test your email system:

// Example test payload
const testEmail = {
  toEmail: "test@example.com",
  subject: "Welcome to Our Store!",
  templateName: "orderConfirmation",
  templateData: {
    orderNumber: "ORD123",
    items: [
      {
        name: "Product 1",
        quantity: 2,
        price: 29.99
      }
    ],
    total: 59.98
  }
};

// Send test email
await fetch('/api/send-email', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(testEmail)
});
Enter fullscreen mode Exit fullscreen mode

Conclusion
Building a professional email system with Next.js and Brevo provides a robust solution for handling all types of email communications. By following this guide, you can implement a scalable and maintainable email system for your applications.

Resources
Brevo API Documentation
Next.js Documentation
Email Template Best Practices

Top comments (0)