Keplers Mail Service

C++

C++ integration examples for Keplers Mail Service

Send emails using C++ with Keplers Mail Service REST API.

Installation

Install libcurl for HTTP requests:

# Ubuntu/Debian
sudo apt-get install libcurl4-openssl-dev

# macOS with Homebrew
brew install curl

# Windows (vcpkg)
vcpkg install curl[core,ssl]

Basic Setup

# .env
KEPLERS_API_KEY=kms_your_api_key.live_...

REST API Integration

Basic Client

#include <curl/curl.h>
#include <string>
#include <iostream>
#include <sstream>
#include <cstdlib>

class KeplersEmailClient {
private:
    std::string apiKey;
    std::string baseUrl;
    
    struct EmailResponse {
        std::string data;
    };
    
    static size_t WriteCallback(void* contents, size_t size, size_t nmemb, EmailResponse* response) {
        size_t totalSize = size * nmemb;
        response->data.append((char*)contents, totalSize);
        return totalSize;
    }
    
    std::string escapeJson(const std::string& input) {
        std::string output;
        for (char c : input) {
            switch (c) {
                case '"': output += "\\\""; break;
                case '\\': output += "\\\\"; break;
                case '\n': output += "\\n"; break;
                case '\r': output += "\\r"; break;
                case '\t': output += "\\t"; break;
                default: output += c; break;
            }
        }
        return output;
    }

public:
    KeplersEmailClient(const std::string& apiKey, const std::string& baseUrl = "https://api.keplars.com") 
        : apiKey(apiKey), baseUrl(baseUrl) {}

    bool sendEmail(const std::string& to, const std::string& subject, 
                   const std::string& body, bool isHtml = false) {
        return makeRequest("/api/v1/send-email/queue", to, subject, body, isHtml);
    }

    bool sendInstantEmail(const std::string& to, const std::string& subject, 
                         const std::string& body, bool isHtml = false) {
        return makeRequest("/api/v1/send-email/instant", to, subject, body, isHtml);
    }

private:
    bool makeRequest(const std::string& endpoint, const std::string& to, 
                    const std::string& subject, const std::string& body, bool isHtml) {
        CURL* curl;
        CURLcode res;
        EmailResponse response;
        
        curl = curl_easy_init();
        if (!curl) {
            std::cerr << "Failed to initialize curl" << std::endl;
            return false;
        }
        
        struct curl_slist* headers = nullptr;
        std::string authHeader = "Authorization: Bearer " + apiKey;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, authHeader.c_str());
        
        std::ostringstream jsonPayload;
        jsonPayload << "{"
                   << "\"to\":[\"" << escapeJson(to) << "\"],"
                   << "\"subject\":\"" << escapeJson(subject) << "\","
                   << "\"body\":\"" << escapeJson(body) << "\","
                   << "\"is_html\":" << (isHtml ? "true" : "false")
                   << "}";
        
        std::string payload = jsonPayload.str();
        std::string url = baseUrl + endpoint;
        
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
        
        res = curl_easy_perform(curl);
        
        long responseCode;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
        
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
        
        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
            return false;
        }
        
        if (responseCode != 200) {
            std::cerr << "HTTP error " << responseCode << ": " << response.data << std::endl;
            return false;
        }
        
        std::cout << "Email sent successfully: " << response.data << std::endl;
        return true;
    }
};

Usage Examples

int main() {
    curl_global_init(CURL_GLOBAL_DEFAULT);
    
    const char* apiKey = std::getenv("KEPLERS_API_KEY");
    if (!apiKey) {
        std::cerr << "KEPLERS_API_KEY environment variable not set" << std::endl;
        return 1;
    }
    
    KeplersEmailClient client(apiKey);
    
    sendWelcomeEmail(client, "[email protected]", "John");
    sendVerificationEmail(client, "[email protected]", "123456");
    
    curl_global_cleanup();
    return 0;
}

bool sendWelcomeEmail(KeplersEmailClient& client, const std::string& email, const std::string& name) {
    std::ostringstream htmlBody;
    htmlBody << "<h1>Welcome " << name << "!</h1>"
             << "<p>Thank you for joining our platform.</p>";
    
    std::string subject = "Welcome " + name + "!";
    
    bool success = client.sendEmail(email, subject, htmlBody.str(), true);
    
    if (success) {
        std::cout << "Welcome email sent to " << email << std::endl;
    } else {
        std::cerr << "Failed to send welcome email to " << email << std::endl;
    }
    
    return success;
}

bool sendVerificationEmail(KeplersEmailClient& client, const std::string& email, const std::string& code) {
    std::string body = "Your verification code: " + code;
    
    bool success = client.sendInstantEmail(email, "Verify Your Email", body, false);
    
    if (success) {
        std::cout << "Verification code sent to " << email << std::endl;
    } else {
        std::cerr << "Failed to send verification code to " << email << std::endl;
    }
    
    return success;
}

Compilation

# Linux/macOS
g++ -std=c++11 -o keplers_email main.cpp -lcurl

# With pkg-config
g++ -std=c++11 $(pkg-config --cflags --libs libcurl) -o keplers_email main.cpp

# Windows (with vcpkg)
cl /EHsc main.cpp /I"path\to\vcpkg\installed\x64-windows\include" /link "path\to\vcpkg\installed\x64-windows\lib\libcurl.lib"

Advanced Usage

class AdvancedKeplersClient : public KeplersEmailClient {
public:
    AdvancedKeplersClient(const std::string& apiKey) : KeplersEmailClient(apiKey) {}
    
    bool sendEmailWithRetry(const std::string& to, const std::string& subject,
                           const std::string& body, bool isHtml = false, int maxRetries = 3) {
        for (int attempt = 1; attempt <= maxRetries; ++attempt) {
            std::cout << "Attempt " << attempt << " of " << maxRetries << std::endl;
            
            if (sendEmail(to, subject, body, isHtml)) {
                return true;
            }
            
            if (attempt < maxRetries) {
                std::this_thread::sleep_for(std::chrono::seconds(attempt));
            }
        }
        
        std::cerr << "Failed to send email after " << maxRetries << " attempts" << std::endl;
        return false;
    }
};

C++ provides powerful email integration capabilities with Keplers Mail Service using libcurl for HTTP requests.

On this page