Rust
Rust integration examples for Keplers Mail Service
Send emails using Rust with Keplers Mail Service REST API.
Installation
Add to your Cargo.toml:
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"Basic Setup
# .env
KEPLERS_API_KEY=kms_your_api_key.live_...REST API Integration
Basic Client
use reqwest;
use serde::{Deserialize, Serialize};
use std::env;
#[derive(Serialize)]
struct EmailRequest {
to: Vec<String>,
subject: String,
body: String,
is_html: bool,
}
#[derive(Deserialize)]
struct EmailResponse {
success: bool,
data: serde_json::Value,
message: Option<String>,
}
pub struct KeplersEmailClient {
client: reqwest::Client,
api_key: String,
base_url: String,
}
impl KeplersEmailClient {
pub fn new(api_key: String) -> Self {
Self {
client: reqwest::Client::new(),
api_key,
base_url: "https://api.keplars.com".to_string(),
}
}
pub async fn send_email(&self, email_data: EmailRequest) -> Result<EmailResponse, Box<dyn std::error::Error>> {
self.make_request("/api/v1/send-email/queue", &email_data).await
}
pub async fn send_instant_email(&self, email_data: EmailRequest) -> Result<EmailResponse, Box<dyn std::error::Error>> {
self.make_request("/api/v1/send-email/instant", &email_data).await
}
async fn make_request(&self, endpoint: &str, data: &EmailRequest) -> Result<EmailResponse, Box<dyn std::error::Error>> {
let response = self
.client
.post(&format!("{}{}", self.base_url, endpoint))
.header("Authorization", format!("Bearer {}", self.api_key))
.header("Content-Type", "application/json")
.json(data)
.send()
.await?;
let email_response: EmailResponse = response.json().await?;
if email_response.success {
Ok(email_response)
} else {
Err(format!("Email sending failed: {:?}", email_response.message).into())
}
}
}Usage Examples
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = env::var("KEPLERS_API_KEY")?;
let client = KeplersEmailClient::new(api_key);
send_welcome_email(&client, "[email protected]", "John").await?;
send_verification_email(&client, "[email protected]", "123456").await?;
Ok(())
}
async fn send_welcome_email(
client: &KeplersEmailClient,
user_email: &str,
user_name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let email_data = EmailRequest {
to: vec![user_email.to_string()],
subject: format!("Welcome {}!", user_name),
body: format!("<h1>Welcome {}!</h1><p>Thank you for joining our platform.</p>", user_name),
is_html: true,
};
match client.send_email(email_data).await {
Ok(response) => {
println!("Email sent: {:?}", response);
Ok(())
}
Err(e) => {
eprintln!("Failed to send email: {}", e);
Err(e)
}
}
}
async fn send_verification_email(
client: &KeplersEmailClient,
user_email: &str,
code: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let email_data = EmailRequest {
to: vec![user_email.to_string()],
subject: "Verify Your Email".to_string(),
body: format!("Your verification code: {}", code),
is_html: false,
};
match client.send_instant_email(email_data).await {
Ok(response) => {
println!("Verification email sent: {:?}", response);
Ok(())
}
Err(e) => {
eprintln!("Failed to send verification email: {}", e);
Err(e)
}
}
}Axum Web Framework Integration
use axum::{
extract::{Json, State},
http::StatusCode,
response::Json as ResponseJson,
routing::post,
Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Deserialize)]
struct SendEmailRequest {
email: String,
name: String,
}
#[derive(Serialize)]
struct ApiResponse {
success: bool,
message: String,
}
type SharedClient = Arc<KeplersEmailClient>;
async fn send_email_handler(
State(client): State<SharedClient>,
Json(payload): Json<SendEmailRequest>,
) -> Result<ResponseJson<ApiResponse>, StatusCode> {
match send_welcome_email(&client, &payload.email, &payload.name).await {
Ok(_) => Ok(ResponseJson(ApiResponse {
success: true,
message: "Email sent successfully".to_string(),
})),
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = env::var("KEPLERS_API_KEY")?;
let client = Arc::new(KeplersEmailClient::new(api_key));
let app = Router::new()
.route("/send-email", post(send_email_handler))
.with_state(client);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
println!("Server running on http://0.0.0.0:3000");
axum::serve(listener, app).await?;
Ok(())
}SMTP Integration
SMTP Installation
[dependencies]
lettre = "0.11"
tokio = { version = "1.0", features = ["full"] }SMTP Client
use lettre::{
message::{header, Mailbox, SinglePart},
transport::smtp::authentication::Credentials,
AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
};
use std::env;
pub struct KeplersEmailSMTPClient {
transport: AsyncSmtpTransport<Tokio1Executor>,
}
impl KeplersEmailSMTPClient {
pub fn new(username: String, password: String) -> Result<Self, Box<dyn std::error::Error>> {
let credentials = Credentials::new(username, password);
let transport = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous("smtp.keplars.com")
.port(587)
.credentials(credentials)
.build();
Ok(Self { transport })
}
pub async fn send_email(&self, email_data: &EmailRequest) -> Result<(), Box<dyn std::error::Error>> {
let from_mailbox: Mailbox = "[email protected]".parse()?;
let to_mailbox: Mailbox = email_data.to[0].parse()?;
let message = if email_data.is_html {
Message::builder()
.from(from_mailbox)
.to(to_mailbox)
.subject(&email_data.subject)
.singlepart(
SinglePart::builder()
.header(header::ContentType::TEXT_HTML)
.body(email_data.body.clone()),
)?
} else {
Message::builder()
.from(from_mailbox)
.to(to_mailbox)
.subject(&email_data.subject)
.singlepart(
SinglePart::builder()
.header(header::ContentType::TEXT_PLAIN)
.body(email_data.body.clone()),
)?
};
self.transport.send(message).await?;
Ok(())
}
}SMTP Usage
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let smtp_client = KeplersEmailSMTPClient::new(
env::var("KEPLERS_SMTP_USERNAME")?,
env::var("KEPLERS_SMTP_PASSWORD")?,
)?;
send_email_via_smtp(&smtp_client, "[email protected]", "Test Email", "<p>Hello World!</p>").await?;
Ok(())
}
async fn send_email_via_smtp(
smtp_client: &KeplersEmailSMTPClient,
user_email: &str,
subject: &str,
body: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let email_data = EmailRequest {
to: vec![user_email.to_string()],
subject: subject.to_string(),
body: body.to_string(),
is_html: true,
};
match smtp_client.send_email(&email_data).await {
Ok(_) => {
println!("SMTP email sent successfully");
Ok(())
}
Err(e) => {
eprintln!("SMTP send failed: {}", e);
Err(e)
}
}
}Choose REST API for advanced features or SMTP for traditional email client integration.