#![forbid(unsafe_code)]
#![warn(missing_docs)]
use std::collections::HashMap;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
const DEFAULT_BASE_URL: &str = "https://vibemail.ai";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_MAX_RETRIES: u32 = 2;
#[derive(Debug, Error)]
pub enum Error {
#[error("vibemail: api {status}: {message}")]
Api {
status: u16,
message: String,
body: String,
retry_after: Option<Duration>,
},
#[error("vibemail: request failed: {0}")]
Request(#[from] reqwest::Error),
#[error("vibemail: decoding response: {0}")]
Decode(#[from] serde_json::Error),
#[error("vibemail: {0}")]
InvalidRecipient(String),
}
impl Error {
pub fn is_retryable(&self) -> bool {
match self {
Error::Api { status, .. } => *status == 429 || *status >= 500,
Error::Request(err) => err.is_timeout() || err.is_connect(),
_ => false,
}
}
pub fn status(&self) -> Option<u16> {
match self {
Error::Api { status, .. } => Some(*status),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct SendRequest {
pub to: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub html: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub variables: Option<HashMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub track_opens: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub track_clicks: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scheduled_at: Option<String>,
}
impl SendRequest {
pub fn new(to: impl Into<String>) -> Self {
Self {
to: to.into(),
..Default::default()
}
}
pub fn from(mut self, from: impl Into<String>) -> Self {
self.from = Some(from.into());
self
}
pub fn subject(mut self, subject: impl Into<String>) -> Self {
self.subject = Some(subject.into());
self
}
pub fn text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
pub fn html(mut self, html: impl Into<String>) -> Self {
self.html = Some(html.into());
self
}
pub fn template(mut self, template: impl Into<String>) -> Self {
self.template = Some(template.into());
self
}
pub fn variable(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.variables
.get_or_insert_with(HashMap::new)
.insert(key.into(), value.into());
self
}
pub fn tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.tags = Some(tags.into_iter().map(Into::into).collect());
self
}
pub fn track_opens(mut self, on: bool) -> Self {
self.track_opens = Some(on);
self
}
pub fn track_clicks(mut self, on: bool) -> Self {
self.track_clicks = Some(on);
self
}
pub fn scheduled_at(mut self, when: impl Into<String>) -> Self {
self.scheduled_at = Some(when.into());
self
}
fn validate(&self, index: Option<usize>) -> Result<(), Error> {
let where_ = index.map_or(String::new(), |i| format!("emails[{i}]: "));
if self.to.trim().is_empty() {
return Err(Error::InvalidRecipient(format!(
"{where_}`to` must contain a recipient address"
)));
}
if self.to.contains(',') {
return Err(Error::InvalidRecipient(format!(
"{where_}`to` takes a single address, use batch() to send to several \
recipients, since one message addressed to many would disclose the list \
to all of them"
)));
}
Ok(())
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct SendResponse {
pub id: String,
pub status: String,
#[serde(default)]
pub scheduled_at: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct BatchResponse {
pub data: Vec<BatchResult>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct BatchResult {
#[serde(default)]
pub id: Option<String>,
pub status: String,
#[serde(default)]
pub error: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Template {
pub id: i64,
pub name: String,
pub subject: String,
#[serde(default)]
pub html_body: Option<String>,
#[serde(default)]
pub text_body: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Page<T> {
#[serde(default)]
pub object: String,
#[serde(default)]
pub total: i64,
#[serde(default)]
pub limit: i64,
#[serde(default)]
pub offset: i64,
#[serde(default = "Vec::new")]
pub data: Vec<T>,
}
#[derive(Debug, Clone, Default)]
pub struct ListOptions {
pub limit: Option<u32>,
pub offset: Option<u32>,
pub search: Option<String>,
}
impl ListOptions {
pub fn new() -> Self {
Self::default()
}
pub fn limit(mut self, n: u32) -> Self {
self.limit = Some(n);
self
}
pub fn offset(mut self, n: u32) -> Self {
self.offset = Some(n);
self
}
pub fn search(mut self, term: impl Into<String>) -> Self {
self.search = Some(term.into());
self
}
fn to_query(&self) -> String {
let mut parts: Vec<String> = Vec::new();
if let Some(n) = self.limit {
parts.push(format!("limit={n}"));
}
if let Some(n) = self.offset {
parts.push(format!("offset={n}"));
}
if let Some(term) = &self.search {
parts.push(format!("search={}", urlencode(term)));
}
if parts.is_empty() {
String::new()
} else {
format!("?{}", parts.join("&"))
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct DnsRecord {
pub r#type: String,
pub host: String,
pub value: String,
#[serde(default)]
pub priority: Option<i32>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Domain {
pub id: i64,
pub domain: String,
#[serde(default)]
pub is_verified: bool,
#[serde(default)]
pub verification_token: Option<String>,
#[serde(default)]
pub created_at: Option<String>,
#[serde(default)]
pub dns_records: Option<HashMap<String, DnsRecord>>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Contact {
pub id: i64,
pub email: String,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub notes: Option<String>,
#[serde(default)]
pub created_at: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Suppression {
pub email: String,
#[serde(default)]
pub reason: Option<String>,
#[serde(default)]
pub created_at: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Deleted {
#[serde(default)]
pub deleted: bool,
#[serde(default)]
pub domain: Option<String>,
#[serde(default)]
pub email: Option<String>,
}
#[derive(Clone)]
pub struct VibeMail {
client: reqwest::Client,
base_url: String,
api_key: String,
max_retries: u32,
}
impl VibeMail {
pub fn new(api_key: impl Into<String>) -> Self {
Self::try_new(api_key).expect("failed to build the HTTP client")
}
pub fn try_new(api_key: impl Into<String>) -> Result<Self, Error> {
Ok(Self {
client: reqwest::Client::builder()
.timeout(DEFAULT_TIMEOUT)
.build()?,
base_url: DEFAULT_BASE_URL.to_string(),
api_key: api_key.into(),
max_retries: DEFAULT_MAX_RETRIES,
})
}
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = base_url.into().trim_end_matches('/').to_string();
self
}
pub fn with_max_retries(mut self, retries: u32) -> Self {
self.max_retries = retries;
self
}
pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
self.client = client;
self
}
pub async fn send(&self, request: SendRequest) -> Result<SendResponse, Error> {
request.validate(None)?;
self.request(reqwest::Method::POST, "/v1/emails", Some(&request), None)
.await
}
pub async fn send_idempotent(
&self,
request: SendRequest,
idempotency_key: impl AsRef<str>,
) -> Result<SendResponse, Error> {
request.validate(None)?;
self.request(
reqwest::Method::POST,
"/v1/emails",
Some(&request),
Some(idempotency_key.as_ref()),
)
.await
}
pub async fn batch(&self, emails: Vec<SendRequest>) -> Result<BatchResponse, Error> {
for (index, email) in emails.iter().enumerate() {
email.validate(Some(index))?;
}
#[derive(Serialize)]
struct Body {
emails: Vec<SendRequest>,
}
self.request(
reqwest::Method::POST,
"/v1/emails/batch",
Some(&Body { emails }),
None,
)
.await
}
pub async fn get(&self, id: &str) -> Result<SendResponse, Error> {
let path = format!("/v1/emails/{}", urlencode(id));
self.request::<(), _>(reqwest::Method::GET, &path, None, None)
.await
}
pub async fn cancel(&self, id: &str) -> Result<SendResponse, Error> {
let path = format!("/v1/emails/{}/cancel", urlencode(id));
self.request::<(), _>(reqwest::Method::POST, &path, None, None)
.await
}
pub async fn templates(&self) -> Result<Vec<Template>, Error> {
self.request::<(), _>(reqwest::Method::GET, "/v1/templates", None, None)
.await
}
pub async fn domains(&self, opts: ListOptions) -> Result<Page<Domain>, Error> {
let path = format!("/v1/domains{}", opts.to_query());
self.request::<(), _>(reqwest::Method::GET, &path, None, None)
.await
}
pub async fn domain(&self, id: &str) -> Result<Domain, Error> {
let path = format!("/v1/domains/{}", urlencode(id));
self.request::<(), _>(reqwest::Method::GET, &path, None, None)
.await
}
pub async fn create_domain(&self, domain: &str) -> Result<Domain, Error> {
#[derive(Serialize)]
struct Body<'a> {
domain: &'a str,
}
self.request(
reqwest::Method::POST,
"/v1/domains",
Some(&Body { domain }),
None,
)
.await
}
pub async fn delete_domain(&self, id: &str) -> Result<Deleted, Error> {
let path = format!("/v1/domains/{}", urlencode(id));
self.request::<(), _>(reqwest::Method::DELETE, &path, None, None)
.await
}
pub async fn contacts(&self, opts: ListOptions) -> Result<Page<Contact>, Error> {
let path = format!("/v1/contacts{}", opts.to_query());
self.request::<(), _>(reqwest::Method::GET, &path, None, None)
.await
}
pub async fn create_contact(
&self,
email: &str,
name: Option<&str>,
notes: Option<&str>,
) -> Result<Contact, Error> {
#[derive(Serialize)]
struct Body<'a> {
email: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
name: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
notes: Option<&'a str>,
}
self.request(
reqwest::Method::POST,
"/v1/contacts",
Some(&Body { email, name, notes }),
None,
)
.await
}
pub async fn delete_contact(&self, id: &str) -> Result<Deleted, Error> {
let path = format!("/v1/contacts/{}", urlencode(id));
self.request::<(), _>(reqwest::Method::DELETE, &path, None, None)
.await
}
pub async fn suppressions(&self, opts: ListOptions) -> Result<Page<Suppression>, Error> {
let path = format!("/v1/suppressions{}", opts.to_query());
self.request::<(), _>(reqwest::Method::GET, &path, None, None)
.await
}
async fn request<B, T>(
&self,
method: reqwest::Method,
path: &str,
body: Option<&B>,
idempotency_key: Option<&str>,
) -> Result<T, Error>
where
B: Serialize + ?Sized,
T: for<'de> Deserialize<'de>,
{
let url = format!("{}{path}", self.base_url);
let mut attempt = 0;
loop {
let mut req = self
.client
.request(method.clone(), &url)
.bearer_auth(&self.api_key)
.header("Accept", "application/json")
.header("User-Agent", format!("vibemail-rust/{VERSION}"));
if let Some(key) = idempotency_key {
req = req.header("Idempotency-Key", key);
}
if let Some(payload) = body {
req = req.json(payload);
}
let outcome = req.send().await;
let error = match outcome {
Ok(res) => {
let status = res.status();
let retry_after = res
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u64>().ok())
.map(Duration::from_secs);
let text = res.text().await?;
if status.is_success() {
let raw = if text.trim().is_empty() { "{}" } else { &text };
return Ok(serde_json::from_str(raw)?);
}
let message = serde_json::from_str::<Value>(&text)
.ok()
.and_then(|v| v.get("error")?.as_str().map(str::to_owned))
.unwrap_or_else(|| text.chars().take(200).collect());
Error::Api {
status: status.as_u16(),
message,
body: text,
retry_after,
}
}
Err(err) => Error::Request(err),
};
if !error.is_retryable() || attempt >= self.max_retries {
return Err(error);
}
let delay = match &error {
Error::Api {
retry_after: Some(d),
..
} => (*d).min(Duration::from_secs(30)),
_ => backoff(attempt),
};
tokio::time::sleep(delay).await;
attempt += 1;
}
}
}
fn backoff(attempt: u32) -> Duration {
Duration::from_millis((500u64 << attempt).min(8_000))
}
fn urlencode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for byte in s.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(byte as char);
}
_ => out.push_str(&format!("%{byte:02X}")),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builder_only_sets_what_was_asked_for() {
let req = SendRequest::new("a@example.com").subject("Hi");
let json = serde_json::to_value(&req).unwrap();
assert_eq!(json["to"], "a@example.com");
assert_eq!(json["subject"], "Hi");
assert!(json.get("html").is_none());
assert!(json.get("tags").is_none());
assert!(json.get("scheduled_at").is_none());
}
#[test]
fn explicit_false_tracking_is_serialized() {
let json = serde_json::to_value(SendRequest::new("a@e.com").track_opens(false)).unwrap();
assert_eq!(json["track_opens"], false);
}
#[test]
fn variables_accumulate() {
let req = SendRequest::new("a@e.com")
.variable("name", "Ada")
.variable("plan", "pro");
let vars = req.variables.unwrap();
assert_eq!(vars.get("name").map(String::as_str), Some("Ada"));
assert_eq!(vars.get("plan").map(String::as_str), Some("pro"));
}
#[test]
fn empty_recipient_is_rejected() {
let err = SendRequest::new(" ").validate(None).unwrap_err();
assert!(matches!(err, Error::InvalidRecipient(_)));
}
#[test]
fn comma_joined_recipients_are_rejected() {
let err = SendRequest::new("a@e.com,b@e.com")
.validate(None)
.unwrap_err();
assert!(err.to_string().contains("batch()"), "{err}");
}
#[test]
fn batch_validation_names_the_offending_entry() {
let err = SendRequest::new("").validate(Some(3)).unwrap_err();
assert!(err.to_string().contains("emails[3]"), "{err}");
}
#[test]
fn retryable_classification() {
let api = |status| Error::Api {
status,
message: String::new(),
body: String::new(),
retry_after: None,
};
assert!(api(429).is_retryable());
assert!(api(500).is_retryable());
assert!(api(503).is_retryable());
assert!(!api(400).is_retryable());
assert!(!api(422).is_retryable());
assert!(!Error::InvalidRecipient("x".into()).is_retryable());
}
#[test]
fn status_is_exposed_for_api_errors_only() {
let api = Error::Api {
status: 422,
message: String::new(),
body: String::new(),
retry_after: None,
};
assert_eq!(api.status(), Some(422));
assert_eq!(Error::InvalidRecipient("x".into()).status(), None);
}
#[test]
fn backoff_grows_then_caps() {
assert_eq!(backoff(0), Duration::from_millis(500));
assert_eq!(backoff(1), Duration::from_millis(1000));
assert_eq!(backoff(2), Duration::from_millis(2000));
assert_eq!(backoff(20), Duration::from_millis(8000));
}
#[test]
fn path_segments_are_escaped() {
assert_eq!(urlencode("a/b"), "a%2Fb");
assert_eq!(urlencode("plain-id_1.2~3"), "plain-id_1.2~3");
assert_eq!(urlencode("../etc"), "..%2Fetc");
}
#[test]
fn base_url_trailing_slash_is_trimmed() {
let c = VibeMail::new("k").with_base_url("http://localhost:8080///");
assert_eq!(c.base_url, "http://localhost:8080");
}
}