DEV Community

Dominique Megnidro
Dominique Megnidro

Posted on

How to Integrate Transactional Emails with Brevo in Your Application

Transactional emails play a crucial role in communicating with your users. Whether it's registration confirmations, password resets, or important notifications, these emails need to be sent reliably and promptly. Brevo (formerly Sendinblue) is a powerful platform that offers transactional email services that are easy to integrate into your application.

In this article, we'll explore how to set up and integrate Brevo's transactional emails into your application. We'll provide concrete examples using Python and the Django framework, but the concepts can be adapted to other languages and frameworks.

1. Why Use Brevo for Transactional Emails

Brevo is an all-in-one platform that offers solutions for marketing emails, transactional emails, SMS, and more. Here are some reasons why Brevo is an excellent choice for transactional emails:

Reliability: High deliverability rates thanks to robust infrastructure.
Ease of Integration: SDKs and RESTful APIs for quick integration.
Customization: Use dynamic templates to personalize emails.
Tracking and Analytics: Detailed statistics on emails sent, opened, clicked, etc.
Scalability: Adapts to your needs, whether you're sending hundreds or millions of emails.

2. Prerequisites

An application (we'll use Django for examples).
Python 3.6 or higher.
A Brevo account (we'll cover how to create one).
Basic knowledge of HTTP and REST APIs.

3. Creating a Brevo Account

Sign Up:

Go to brevo.com.
Click on "Sign Up" and fill out the form.
Confirm your email address.
Choose a Plan:

Brevo offers a free plan that allows you to send up to 300 emails per day.
For larger needs, choose a plan that fits your requirements.

4. Brevo Configuration

4.1. Verifying Your Sending Domain
To improve deliverability and prevent your emails from landing in spam, it's recommended to verify your domain.

Navigate to: Settings > Email Settings > Sending Domains.
Add your domain by clicking on "Add a domain".
Follow the instructions to add the provided DNS records (SPF, DKIM) from Brevo to your domain host.
Verify that the domain has been validated.
4.2. Obtaining the API Key
Navigate to: Settings > API Keys.
Create a new API key by clicking on "Generate a new API key".
Name your API key (e.g., "API Key for Django Application").
Copy the generated API key and keep it secure.

5. Integration into a Django Application

5.1. Installing the Brevo SDK
Brevo provides a Python SDK to facilitate integration.

Install via pip:

pip install sib-api-v3-sdk
Enter fullscreen mode Exit fullscreen mode

5.2. Configuration in settings.py
Add the necessary configurations to your settings.py file.

# settings.py

import os

# ...

# Brevo configuration
BREVO_API_KEY = os.environ.get('BREVO_API_KEY')

# Optional: Configure Django's email backend to use Brevo SMTP
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp-relay.brevo.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'your_email_address'
EMAIL_HOST_PASSWORD = BREVO_API_KEY
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'your_email_address'

Enter fullscreen mode Exit fullscreen mode

Note: It's recommended to use environment variables to store sensitive keys like BREVO_API_KEY.

5.3. Sending a Transactional Email

Example Code:

# adapter.py
from allauth.account.adapter import DefaultAccountAdapter
from django.conf import settings
from django.template.loader import render_to_string
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from django.contrib.sites.shortcuts import get_current_site

class CustomAccountAdapter(DefaultAccountAdapter):
    def send_confirmation_mail(self, request, emailconfirmation, signup):
        # Générer l'URL de confirmation
        activate_url = self.get_email_confirmation_url(request, emailconfirmation)
        # Obtenir le site actuel
        current_site = get_current_site(request)
        context = {
            'user': emailconfirmation.email_address.user,
            'activate_url': activate_url,
            'current_site': current_site,
            'key': emailconfirmation.key,
            'signup': signup,
        }
        # Rendre les templates
        subject = render_to_string('account/email/email_confirmation_subject.txt', context).strip()
        message = render_to_string('account/email/email_confirmation_message.html', context)
        # Configurer l'API Brevo
        configuration = sib_api_v3_sdk.Configuration()
        configuration.api_key['api-key'] = settings.BREVO_API_KEY
        api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
        # Créer l'email

        # Créer l'email avec le sender
        send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
            sender={
                "email": settings.BREVO_SENDER['EMAIL'],
                "name": settings.BREVO_SENDER['NAME']
            },
            to=[{
                "email": emailconfirmation.email_address.email,
                "name": emailconfirmation.email_address.user.email
            }],
            subject=subject,
            html_content=message,
        )

        # Envoyer l'email
        try:
            api_instance.send_transac_email(send_smtp_email)
        except ApiException as e:
            print(f"Erreur lors de l'envoi de l'email de confirmation : {e}")

Enter fullscreen mode Exit fullscreen mode

Usage in your view

# views.py

from django.shortcuts import render
from .adaptater import send_transactional_email

def register_user(request):
    if request.method == 'POST':
        # User registration logic
        # ...

        # Send confirmation email
        subject = "Welcome to Our Platform"
        content = "<h1>Thank you for signing up!</h1><p>We're excited to have you with us.</p>"
        send_transactional_email(user.email, subject, content)

        return render(request, 'registration_success.html')
    else:
        return render(request, 'register.html')

Enter fullscreen mode Exit fullscreen mode

6. Using Email Templates

Rather than coding the HTML content directly into your application, you can create templates in Brevo for easier management.

6.1. Creating a Template in Brevo
Navigate to: Templates > My Templates.
Create a new template by clicking on "Create a New Template".
Name your template (e.g., "Registration Confirmation").
Use the editor to design your email.
Save the template.
6.2. Sending an Email Using a Template
Example Code:


def send_transactional_email_with_template(to_email, template_id, params):
    configuration = Configuration()
    configuration.api_key['api-key'] = settings.BREVO_API_KEY

    api_instance = transactional_emails_api.TransactionalEmailsApi(ApiClient(configuration))

    send_smtp_email = SendSmtpEmail(
        to=[{"email": to_email}],
        template_id=template_id,
        params=params
    )

    try:
        api_response = api_instance.send_transac_email(send_smtp_email)
        print(f"Email sent: {api_response.message_id}")
    except Exception as e:
        print(f"Error sending email: {e}")
Enter fullscreen mode Exit fullscreen mode

Usage in your views

# views.py

def register_user(request):
    if request.method == 'POST':
        # User registration logic
        # ...

        # Send confirmation email with template
        template_id = 1  # Replace with your template ID
        params = {
            'USERNAME': user.username,
            'ACTIVATION_LINK': activation_link,
        }
        send_transactional_email_with_template(user.email, template_id, params)

        return render(request, 'registration_success.html')
    else:
        return render(request, 'register.html')

Enter fullscreen mode Exit fullscreen mode

Note: The params correspond to the dynamic variables used in your Brevo template (e.g., {{ params.USERNAME }}).

7. Handling Events and Webhooks

To track events such as opens, clicks, bounces, or unsubscribes, you can configure webhooks in Brevo.

Navigate to: Settings > Webhooks.
Create a new webhook by clicking on "Add a webhook".
Select the events you want to track.
Provide the URL of your application where notifications should be sent.
Implement a view in your application to handle the received data.
Example View to Receive Webhooks:

# urls.py

from django.urls import path
from . import views

urlpatterns = [
    # ...
    path('webhook/brevo/', views.brevo_webhook, name='brevo_webhook'),
]

# views.py

import json
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def brevo_webhook(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        event = data.get('event')
        email = data.get('email')
        # Handle different events here
        if event == 'opened':
            print(f"Email opened by {email}")
        elif event == 'clicked':
            print(f"Email clicked by {email}")
        # ...
        return HttpResponse(status=200)
    else:
        return HttpResponse(status=405)

Enter fullscreen mode Exit fullscreen mode

8. Best Practices and Security Considerations

Never store the API key in plain text in your code or repository. Use environment variables.
Validate data before including it in emails to prevent code injection.
Handle exceptions when sending emails to prevent errors from disrupting your application's flow.
Test in a development environment before moving to production.
Comply with regulations regarding emailing (GDPR, CAN-SPAM Act, etc.).

9. Conclusion

Integrating transactional emails with Brevo into your application is an effective way to enhance communication with your users. With its powerful features and user-friendly API, you can quickly set up a reliable and scalable emailing system.

By following the steps in this article, you should be able to:

Set up your Brevo account and verify your domain.
Integrate sending transactional emails into your Django application.
Use templates to personalize your emails.
Handle events and webhooks for precise tracking.
Feel free to explore more of Brevo's features to get the most out of their platform.

Thank you for reading this article! If you have any questions or comments, feel free to share them below.

Top comments (0)