configure your WordPress site to send emails via the Brevo API without plugin

PHOTO EMBED

Tue Aug 06 2024 00:28:42 GMT+0000 (Coordinated Universal Time)

Saved by @Y@sir #custom #smtp #smtpwithoutplugin


/**configure your WordPress site to send emails via the Brevo API**/

function send_email_via_brevo($to, $subject, $message, $headers = '', $attachments = []) {
    $api_url = 'https://api.brevo.com/v3/smtp/email';
    $api_key = '123'; // Your Brevo API key

    // Email data structure
    $email_data = [
        'sender' => [
            'email' => 'contact@example.com', // Your email address
            'name' => 'Your Name' // Your name
        ],
        'to' => [
            [
                'email' => $to, // Recipient's email
                'name' => '' // Recipient's name (optional)
            ]
        ],
        'subject' => $subject,
        'htmlContent' => $message
    ];

    // Headers for the API request
    $request_headers = [
        'Content-Type: application/json',
        'api-key: ' . $api_key
    ];

    // Arguments for the API request
    $args = [
        'body' => json_encode($email_data),
        'headers' => $request_headers,
        'method' => 'POST',
        'data_format' => 'body'
    ];

    // Send the API request
    $response = wp_remote_post($api_url, $args);

    // Handle any errors
    if (is_wp_error($response)) {
        error_log('Email sending failed: ' . $response->get_error_message());
        return false;
    }

    // Log the response
    $response_body = wp_remote_retrieve_body($response);
    error_log('Email sent response: ' . $response_body);

    return true;
}

function override_wp_mail($args) {
    return send_email_via_brevo($args['to'], $args['subject'], $args['message'], $args['headers'], $args['attachments']);
}

add_filter('wp_mail', 'override_wp_mail', 10, 1);

content_copyCOPY