Send a transactional email

Learn how to send a transactional email for an existing template and adding dynamic content

Transactional emails are used for all non-promotional emails: send them when a user has created an account, when they have made an order, when request a new password...

👍

What you will learn from this tutorial

In this tutorial, you will learn how to:

  • send a basic transactional email with a dummy HTML content.

  • send a transactional email where we'll insert dynamic contact attributes (ex. contact name, address) and transactional parameters (ex. order number, expected date of delivery).

Requirements

Get your API keyAPI key - The unique identifier related to your account that is used to authenticate requests made to SendinBlue API. Get it from your settings (SMTP & API) and pass it to your request header under the key `api-key`. from your settings (SMTP & API).

If you are new to the API, read more about how the api works.

Send a transactional email using a basic HTML content

Let's assume we would like to send the following basic email.

HTML content

<html><head></head><body><p>Hello,</p>This is my first transactional email sent from Sendinblue.</p></body></html>

Email subject

"Hello worldl"

Sender name

"Sender Alex"

Sender email

"email":"[email protected]"

Recipient name

"John Doe"

Recipient email

"email":"[email protected]"

The HTTP request to send using cURL is the following:

curl --request POST \
  --url https://api.sendinblue.com/v3/smtp/email \
  --header 'accept: application/json' \
  --header 'api-key:YOUR_API_KEY' \
  --header 'content-type: application/json' \
  --data '{  
   "sender":{  
      "name":"Sender Alex",
      "email":"[email protected]"
   },
   "to":[  
      {  
         "email":"[email protected]",
         "name":"John Doe"
      }
   ],
   "subject":"Hello world",
   "htmlContent":"<html><head></head><body><p>Hello,</p>This is my first transactional email sent from Sendinblue.</p></body></html>"
}'

Send a transactional email containing dynamic contact attributes and transactional parameters

In this tutorial, we'll be sending an order confirmation email to a contact, where we'll insert dynamic contact attributes (contact name, address) and transactional parameters (order number, expected date of delivery).

For the sake of simplicity, we'll use an existing email template to design our email.

This is the email you should get by the end of the tutorial:

Create a test template that includes dynamic content

To get started quickly, let's create the email template from Sendinblue dashboard.

  1. First, go to the template creation page
  2. Choose your settings and click Next Step
  • Under Template Name, enter "Order confirmation"
  • Under Subject Line, enter "Your new order has been received"
  • Pick an existing sender for the From Email
  • Enter your company name under From Name
  1. Once directed the Design tab, select the "Import a template" tab, and copy and paste the following Shared Template URL: https://my.sendinblue.com/iNF7GRiE34wzuyVRWobyyLLNbttWwwKn8CQLDhU7kui0HXu4tZG_ZzZ6Ng--
  1. Click "Import" next to the URL. You should be redirected to the following page bellow.
    Click the "Save & Quit" button, then on the new page " Save and Activate".
  1. Go back to the templates page and save the template id of the one you just created for later. The id of the template is the number after the "#" after the template name.

📘

Template creation using the API

Creating a template using the API is possible, but more limited. Using the Create an smtp template endpoint, you can create a template:

  • by passing the html content as a string (htmlContent)
  • by passing the html content available at a URL (htmlUrl)

Add a contact attribute for the delivery address

By default, a contact comes with the attributes EMAIL, FIRSTNAME, LASTNAME, SMS. Let's add the DELIVERYADDRESS so we can use it fill our template when sending an email.

  1. Go to the contact attributes page (under Contact > Settings > Contact Attributes & CRM) and add a new field DELIVERYADDRESS.
  1. Go to your contact page and add a new contact:

    FIRSTNAME: Thomas
    LASTNAME: Bianchi
    EMAIL: set up your email to receive the test email
    DELIVERYADDRESS: 176 Boulevard des fleurs, 75014 Paris, France
    Select any you want to import this contact into

  1. Click " Save and Close".

📘

Managing contacts

:bulb: These features are also available through the API. The endpoints that will help you are Creates contact attribute and Create a contact. You can also follow the tutorial on how to synchronise contact lists to be guided through the steps.

:+1: That's it! Now let's send our first email!

Send your transactional email

Let's learn how to use the API. The best way to know what's possible and how to use each endpoint is to go to the API Reference.

Under SMTP > Send a transactional email, you can find the description of the endpoint:

1. Generate a code snippet to quickly test your request:

  1. Enter the body and path parameters to send in your request. These are the ones we'll need:
  • sender: Enter your sender email and name
    :bulb: the sender email must be a sender registered and verified in Sendinblue
    :bulb: the sender name parameter here can override the default sender name you have set
  • to: Enter your recipient email and name
    :bulb: the recipient email should be a contact registered in Sendinblue and assigned to a contact list. That contact should have the attributes FIRSTNAME, LASTNAME, EMAIL, DELIVERYADDRESS defined.
    :bulb: the recipient name here is the name that will be attached to the email recipient. It will appear in the email headers/metadata and not in the email body.
  • templateId : Enter your template id
    Get the list from the templates page or using the endpoint to get the list of SMTP templates
  • params: the value we will use is {"ORDER": 12345, "DATE": "12/06/2019"}
  1. Try out the endpoint from the interface. For that, click the " Try it" button and enter you API key
  • If everything goes well, you should get a success response (code 201) with a JSON body giving you the id of the message sent. ex: {"messageId":"<[email protected]>"}.
  • Notice that the order number and delivery date will be missing from the email received. The reason is that using the API reference interface, you cannot specify rich JSON body parameters like the params to provide DATE and ORDER, so you'll have to use the code snippets and test using cURL or using other integrations. Go to next section for more details.
  • If the parameters you entered are wrong, you'll get a 400 error along with an error message and error code. Find the list of errors here.

🚧

API Reference limitations and rating

When you try an endpoint, you will make a real call to the API.
Make sure to check rate limits and your credits as the API reference will use them to make the requests (when sending an email or an sms for instance).

Read more about SendinBlue sending email bandwidth and quota

Creating your API request using Sendinblue API clients:

The code snippets in the API Reference are only there for you to test your API quickly and in the language that suits you.

:+1: For your integration, we recommend you use our API clients that will provide you with shortcuts and ease of integration.
Available API clientsAPI clients - To make coding against APIs easier, SendinBlue provides client libraries that can reduce the amount of code you need to write and make your code more robust. A client library is a set of code that developers can add to their projects. It provides chunks of code that do the basic things an application needs to do in order to interact with the API. and their documentations: C#, Go, Java, Node JS, PHP, Python, Ruby.

Here are sample codes using the API clientsAPI clients - To make coding against APIs easier, SendinBlue provides client libraries that can reduce the amount of code you need to write and make your code more robust. A client library is a set of code that developers can add to their projects. It provides chunks of code that do the basic things an application needs to do in order to interact with the API.. Before using then, follow the installation guide from each documentation linked above.

curl --request POST \
  --url https://api.sendinblue.com/v3/smtp/email \
  --header 'accept: application/json' \
  --header 'api-key:YOUR_API_KEY' \
  --header 'content-type: application/json' \
  --data '{  
   "to":[  
      {  
         "email":"[email protected]",
         "name":"John Doe"
      }
   ],
   "templateId":8,
   "params":{  
      "name":"John",
      "surname":"Doe"
   },
   "headers":{  
      "X-Mailin-custom":"custom_header_1:custom_value_1|custom_header_2:custom_value_2|custom_header_3:custom_value_3",
      "charset":"iso-8859-1"
   }
}'
curl --request POST \
  --url https://api.sendinblue.com/v3/smtp/email \
  --header 'accept: application/json' \
  --header 'api-key:YOUR_API_KEY' \
  --header 'content-type: application/json' \
  --data '{  
   "sender":{  
      "name":"Sender Alex",
      "email":"[email protected]"
   },
   "to":[  
      {  
         "email":"[email protected]",
         "name":"John Doe"
      }
   ],
   "subject":"test mail",
   "htmlContent":"<html><head></head><body><h1>Hello this is a test email from sib</h1></body></html>",
   "headers":{  
      "X-Mailin-custom":"custom_header_1:custom_value_1|custom_header_2:custom_value_2|custom_header_3:custom_value_3",
      "charset":"iso-8859-1"
   }
}'
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: api-key
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');

// Uncomment below line to configure authorization using: partner-key
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('partner-key', 'YOUR_API_KEY');

$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(
    // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
    // This is optional, `GuzzleHttp\Client` will be used as default.
    new GuzzleHttp\Client(),
    $config
);
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail(); // \SendinBlue\Client\Model\SendSmtpEmail | Values to send a transactional email
$sendSmtpEmail['to'] = array(array('email'=>'[email protected]', 'name'=>'John Doe'));
$sendSmtpEmail['templateId'] = 59;
$sendSmtpEmail['params'] = array('name'=>'John', 'surname'=>'Doe');
$sendSmtpEmail['headers'] = array('X-Mailin-custom'=>'custom_header_1:custom_value_1|custom_header_2:custom_value_2');

try {
    $result = $apiInstance->sendTransacEmail($sendSmtpEmail);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling TransactionalEmailsApi->sendTransacEmail: ', $e->getMessage(), PHP_EOL;
}
?>
var SibApiV3Sdk = require('sib-api-v3-sdk');
var defaultClient = SibApiV3Sdk.ApiClient.instance;

// Configure API key authorization: api-key
var apiKey = defaultClient.authentications['api-key'];
apiKey.apiKey = 'YOUR_API_KEY';

// Uncomment below two lines to configure authorization using: partner-key
// var partnerKey = defaultClient.authentications['partner-key'];
// partnerKey.apiKey = 'YOUR API KEY';

var apiInstance = new SibApiV3Sdk.TransactionalEmailsApi();

var sendSmtpEmail = new SibApiV3Sdk.SendSmtpEmail(); // SendSmtpEmail | Values to send a transactional email

sendSmtpEmail = {
    to: [{
        email: '[email protected]',
        name: 'John Doe'
    }],
    templateId: 59,
    params: {
        name: 'John',
        surname: 'Doe'
    },
    headers: {
        'X-Mailin-custom': 'custom_header_1:custom_value_1|custom_header_2:custom_value_2'
    }
};

apiInstance.sendTransacEmail(sendSmtpEmail).then(function(data) {
  console.log('API called successfully. Returned data: ' + data);
}, function(error) {
  console.error(error);
});
# load the gem
require 'sib-api-v3-sdk'
# setup authorization
SibApiV3Sdk.configure do |config|
  # Configure API key authorization: api-key
  config.api_key['api-key'] = 'YOUR_API_KEY'

  # Uncomment below line to configure API key authorization using: partner-key
  # config.api_key['partner-key'] = 'YOUR API KEY'

end

api_instance = SibApiV3Sdk::TransactionalEmailsApi.new

send_smtp_email = SibApiV3Sdk::SendSmtpEmail.new # SendSmtpEmail | Values to send a transactional email

send_smtp_email = {
  'to'=>[{
    'email'=>'[email protected]',
    'name'=>'John Doe'
  }],
  'templateId'=>59,
  'params'=> {
    'name'=>'John',
    'surname'=>'Doe'
  },
  'headers'=> {
    'X-Mailin-custom'=>'custom_header_1:custom_value_1|custom_header_2:custom_value_2'
  }
};

begin
  #Send a transactional email
  result = api_instance.send_transac_email(send_smtp_email)
  p result
rescue SibApiV3Sdk::ApiError => e
  puts "Exception when calling TransactionalEmailsApi->send_transac_email: #{e}"
end
from __future__ import print_function
import time
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint

# Configure API key authorization: api-key
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = 'YOUR_API_KEY'

# Uncomment below lines to configure API key authorization using: partner-key
# configuration = sib_api_v3_sdk.Configuration()
# configuration.api_key['partner-key'] = 'YOUR_API_KEY'

# create an instance of the API class
api_instance = sib_api_v3_sdk.SMTPApi(sib_api_v3_sdk.ApiClient(configuration))
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=[{"email":"[email protected]","name":"John Doe"}], template_id=56, params={"name": "John", "surname": "Doe"}, headers={"X-Mailin-custom": "custom_header_1:custom_value_1|custom_header_2:custom_value_2|custom_header_3:custom_value_3", "charset": "iso-8859-1"}) # SendSmtpEmail | Values to send a transactional email

try:
    # Send a transactional email
    api_response = api_instance.send_transac_email(send_smtp_email)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
// This example is for Typescript-node

var SibApiV3Sdk = require('sib-api-v3-typescript');

var apiInstance = new SibApiV3Sdk.SMTPApi()

// Configure API key authorization: api-key

var apiKey = apiInstance.authentications['apiKey'];
apiKey.apiKey = "YOUR API KEY"

// Configure API key authorization: partner-key

var partnerKey = apiInstance.authentications['partnerKey'];
partnerKey.apiKey = "YOUR API KEY"

var sendSmtpEmail = {
    to: [{
        email: '[email protected]',
        name: 'John Doe'
    }],
    templateId: 59,
    params: {
        name: 'John',
        surname: 'Doe'
    },
    headers: {
        'X-Mailin-custom': 'custom_header_1:custom_value_1|custom_header_2:custom_value_2'
    }
};


apiInstance.sendTransacEmail(sendSmtpEmail).then(function(data) {
  console.log('API called successfully. Returned data: ' + data);
}, function(error) {
  console.error(error);
});

👍

For each request, make sure to include the following headers:

  • api-key: xkeysib-xxxxxxxxxxxxxxxxx
  • content-type: application/json
  • accept: application/json

:+1: Check your emails! Congratulations, you've just sent your first transactional email using Sendinblue API!


Tracking your transactional activity through Webhooks.

If you would like to additionally track the status of your message there's a number of events you can look after with webhooks. Here is the full list:

Sent , Delivered, Opened, Clicked, Soft Bounce, Hard Bounce, Invalid Email, Deferred, Complaint, Unsubscribed, Blocked, Error.


  1. We must create a webhook definition to which we will be posting all the event data. This can be easily done through the transactional webhooks page. . Here you need to specify the URL of the server which will be receiving the incoming data from Sendinblue. Also, you need to check which events you are interested to track.

transactional webhooks page

📘

Managing Webhooks

You can also do these actions straight from the API, if you prefer. The endpoints that will help you are Create a webhook and Update a webhook in case you want to change the webhook definition.



  1. We chose to track the delivered event in the previous step. Sendinblue will post the event specific data to your URL every time a transactional email is delivered to the recipient's inbox. Let's send another email:
curl --request POST \
  --url https://api.sendinblue.com/v3/smtp/email \
  --header 'accept: application/json' \
  --header 'api-key: xkeysib-xxxxxxxxxxx' \
  --header 'content-type: application/json' \
  --data '{
  "sender":{"email":"[email protected]"},
  "to":[{"email":"[email protected]"}],
  "replyTo":{"email":"[email protected]"},
  "textContent":"This is a transactional email",
  "subject":"Subject Line",
  "tags":["myFirstTransactional"]
  }'

📘

Pro Tip

When sending a transactional email you can also pass the tags object to specify a custom flag or identifier which could help you query through the received events on your side.



  1. Once our message is delivered the following data will be posted to your URL. You can expect the same structure every time an event of the same kind is triggered.
{
  "event": "delivered",
  "email": "[email protected]",
  "id": 26224,
  "date": "YYYY-MM-DD HH:mm:ss",
  "ts": 1598634509,
  "message-id": "<[email protected]>",
  "ts_event": 1598034509,
  "subject": "Subject Line",
  "tag": "[\"transactionalTag\"]",
  "sending_ip": "185.41.28.109",
  "ts_epoch": 1598634509223,
  "tags": [
    "myFirstTransactional"
  ]
}

Note: You can take a closer look to all the event specific payload in this help article.

Updated 10 days ago


Send a transactional email


Learn how to send a transactional email for an existing template and adding dynamic content

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.


Got a minute?