Pages

Friday, 2 June 2023

How to send emails to your users from your website using Brevo (SendInBlue) API in PHP?

Below PHP code demonstrates how to send emails from your website using Brevo (SendInBlue) API in PHP. You should have API key handy before using this code. Please put entire code in try catch block.

//Set endpoint and api key

$endpoint = 'https://api.brevo.com/v3/smtp/email';

$api_key = 'YOUR_API_KEY';

//Request payload

$data = array(

    'sender' => array(

        'name' => 'Sender Alex',

        'email' => 'senderalex@example.com'

    ),

    'to' => array(

        array(

            'email' => 'testmail@example.com',

            'name' => 'John Doe'

        )

    ),

    'subject' => 'Hello world',

    'htmlContent' => '<html><head></head><body><p>Hello,</p><p>This is my first transactional email sent from Brevo.</p></body></html>'

);

//Set cURL options

$options = array(

    CURLOPT_URL => $endpoint,

    CURLOPT_POST => true,

    CURLOPT_POSTFIELDS => json_encode($data),

    CURLOPT_RETURNTRANSFER => true,

    CURLOPT_HTTPHEADER => array(

        'accept: application/json',

        'api-key: ' . $api_key,

        'content-type: application/json'

    )

);

//Initialize cURL session

$curl = curl_init();

//Set cURL options

curl_setopt_array($curl, $options);

//Execute the request

$response = curl_exec($curl);

//Check for errors

if ($response === false) {

    echo 'Error: ' . curl_error($curl);

} else {

    //Process the response

    $response_data = json_decode($response, true);

    if (isset($response_data['message'])) {

        echo 'Email sent successfully!';

    } else {

        echo 'Email sending failed. Error: ' . $response_data['error'];

    }

}

//Close cURL session

curl_close($curl);

No comments:

Post a Comment