Language SDKs & Integration
Complete integration guides for sending instant emails with different programming languages
Language SDKs & Integration
Comprehensive guides for sending instant emails with Keplers Mail Service using different programming languages. All examples use the /instant endpoint for immediate delivery.
Supported Languages
NodeJS
- Runtime: Node.js 16+
- HTTP Client: axios, fetch
- Use Cases: 2FA codes, OTP verification, password reset
Go
- Versions: Go 1.19+
- HTTP Client: net/http
- Use Cases: High-performance email sending, microservices
Python
- Versions: Python 3.8+
- HTTP Client: requests, httpx
- Use Cases: Data processing, automation, web apps
Dart
- Versions: Dart 2.17+
- HTTP Client: http package
- Use Cases: Flutter apps, server-side Dart
Ruby
- Versions: Ruby 3.0+
- HTTP Client: net/http, HTTParty
- Use Cases: Rails applications, automation scripts
Rust
- HTTP Client: reqwest, tokio
- Use Cases: High-performance systems, WebAssembly
C++
- HTTP Client: libcurl, cpprest
- Use Cases: System-level applications, embedded systems
iOS Swift
- Versions: Swift 5.5+
- HTTP Client: URLSession
- Use Cases: iOS applications, native mobile apps
Quick Start Examples
NodeJS
const axios = require('axios');
async function sendInstantEmail(to, subject, body, isHTML = false) {
try {
const response = await axios.post(
'https://api.keplars.com/api/v1/send-email/instant',
{
to: [to],
subject: subject,
body: body,
is_html: isHTML
},
{
headers: {
'Authorization': `Bearer ${process.env.KEPLERS_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
return response.data;
} catch (error) {
throw new Error(`Failed to send email: ${error.response?.data?.message || error.message}`);
}
}
// Usage
sendInstantEmail('[email protected]', 'Your verification code', 'Code: 123456');Go
package main
import (
"bytes"
"encoding/json"
"net/http"
"os"
)
type EmailRequest struct {
To []string `json:"to"`
Subject string `json:"subject"`
Body string `json:"body"`
IsHTML bool `json:"is_html"`
}
func sendInstantEmail(to, subject, body string, isHTML bool) error {
email := EmailRequest{
To: []string{to},
Subject: subject,
Body: body,
IsHTML: isHTML,
}
jsonData, _ := json.Marshal(email)
req, _ := http.NewRequest("POST", "https://api.keplars.com/api/v1/send-email/instant", bytes.NewBuffer(jsonData))
req.Header.Set("Authorization", "Bearer "+os.Getenv("KEPLERS_API_KEY"))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}Python
import requests
import os
def send_instant_email(to, subject, body, is_html=False):
try:
response = requests.post(
'https://api.keplars.com/api/v1/send-email/instant',
json={
'to': [to],
'subject': subject,
'body': body,
'is_html': is_html
},
headers={
'Authorization': f'Bearer {os.getenv("KEPLERS_API_KEY")}',
'Content-Type': 'application/json'
}
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise Exception(f'Failed to send email: {str(e)}')
# Usage
send_instant_email('[email protected]', 'Your verification code', 'Code: 123456')Dart
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<Map<String, dynamic>> sendInstantEmail(
String to, String subject, String body, {bool isHtml = false}) async {
try {
final response = await http.post(
Uri.parse('https://api.keplars.com/api/v1/send-email/instant'),
headers: {
'Authorization': 'Bearer ${Platform.environment['KEPLERS_API_KEY']}',
'Content-Type': 'application/json',
},
body: jsonEncode({
'to': [to],
'subject': subject,
'body': body,
'is_html': isHtml,
}),
);
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to send email: ${response.body}');
}
} catch (e) {
throw Exception('Failed to send email: $e');
}
}
// Usage
// sendInstantEmail('[email protected]', 'Your verification code', 'Code: 123456');Ruby
require 'net/http'
require 'json'
def send_instant_email(to, subject, body, is_html: false)
uri = URI('https://api.keplars.com/api/v1/send-email/instant')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{ENV['KEPLERS_API_KEY']}"
request['Content-Type'] = 'application/json'
request.body = {
to: [to],
subject: subject,
body: body,
is_html: is_html
}.to_json
response = http.request(request)
if response.code == '200'
JSON.parse(response.body)
else
raise "Failed to send email: #{response.body}"
end
end
# Usage
# send_instant_email('user@example.com', 'Your verification code', 'Code: 123456')Rust
use reqwest;
use serde_json::json;
use std::env;
use std::collections::HashMap;
#[tokio::main]
async fn send_instant_email(
to: &str,
subject: &str,
body: &str,
is_html: bool
) -> Result<HashMap<String, serde_json::Value>, reqwest::Error> {
let client = reqwest::Client::new();
let api_key = env::var("KEPLERS_API_KEY").expect("KEPLERS_API_KEY must be set");
let payload = json!({
"to": [to],
"subject": subject,
"body": body,
"is_html": is_html
});
let response = client
.post("https://api.keplars.com/api/v1/send-email/instant")
.header("Authorization", format!("Bearer {}", api_key))
.header("Content-Type", "application/json")
.json(&payload)
.send()
.await?;
let result: HashMap<String, serde_json::Value> = response.json().await?;
Ok(result)
}
// Usage
// let result = send_instant_email("[email protected]", "Your verification code", "Code: 123456", false).await;C++
#include <curl/curl.h>
#include <string>
#include <iostream>
#include <cstdlib>
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;
}
int sendInstantEmail(const std::string& to, const std::string& subject, const std::string& body, bool isHtml = false) {
CURL* curl;
CURLcode res;
EmailResponse response;
curl = curl_easy_init();
if (curl) {
// Get API key from environment
const char* apiKey = std::getenv("KEPLERS_API_KEY");
if (!apiKey) {
std::cerr << "KEPLERS_API_KEY environment variable not set" << std::endl;
return 1;
}
// Prepare headers
struct curl_slist* headers = NULL;
std::string authHeader = "Authorization: Bearer " + std::string(apiKey);
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, authHeader.c_str());
// Prepare JSON payload
std::string jsonPayload = "{"
"\"to\":[\"" + to + "\"],"
"\"subject\":\"" + subject + "\","
"\"body\":\"" + body + "\","
"\"is_html\":" + (isHtml ? "true" : "false") +
"}";
curl_easy_setopt(curl, CURLOPT_URL, "https://api.keplars.com/api/v1/send-email/instant");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonPayload.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
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 1;
}
std::cout << "Response: " << response.data << std::endl;
return 0;
}
return 1;
}
// Usage
// sendInstantEmail("[email protected]", "Your verification code", "Code: 123456", false);iOS Swift
import Foundation
func sendInstantEmail(to: String, subject: String, body: String, isHTML: Bool = false, completion: @escaping (Result<[String: Any], Error>) -> Void) {
guard let apiKey = ProcessInfo.processInfo.environment["KEPLERS_API_KEY"] else {
completion(.failure(NSError(domain: "KeplersEmail", code: 1, userInfo: [NSLocalizedDescriptionKey: "KEPLERS_API_KEY not found"])))
return
}
guard let url = URL(string: "https://api.keplars.com/api/v1/send-email/instant") else {
completion(.failure(NSError(domain: "KeplersEmail", code: 2, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])))
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let payload: [String: Any] = [
"to": [to],
"subject": subject,
"body": body,
"is_html": isHTML
]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: payload)
} catch {
completion(.failure(error))
return
}
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "KeplersEmail", code: 3, userInfo: [NSLocalizedDescriptionKey: "No data received"])))
return
}
do {
if let jsonResponse = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
completion(.success(jsonResponse))
} else {
completion(.failure(NSError(domain: "KeplersEmail", code: 4, userInfo: [NSLocalizedDescriptionKey: "Invalid response format"])))
}
} catch {
completion(.failure(error))
}
}.resume()
}
// Usage
// sendInstantEmail(to: "[email protected]", subject: "Your verification code", body: "Code: 123456") { result in
// switch result {
// case .success(let response):
// print("Email sent: \(response)")
// case .failure(let error):
// print("Error: \(error.localizedDescription)")
// }
// }For complete language-specific implementation guides, select your preferred language from the sidebar.