lettr 1.1.0

Official Rust SDK for the Lettr Email API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use std::sync::Arc;

use reqwest::Method;
use serde::{Deserialize, Serialize};

use crate::config::Config;

// ── Enum Types ────────────────────────────────────────────────────────────

/// Status of a sending domain.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DomainStatus {
    Pending,
    Approved,
    Blocked,
    /// An unknown status not yet covered by this enum.
    #[serde(untagged)]
    Unknown(String),
}

impl std::fmt::Display for DomainStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pending => write!(f, "pending"),
            Self::Approved => write!(f, "approved"),
            Self::Blocked => write!(f, "blocked"),
            Self::Unknown(s) => write!(f, "{s}"),
        }
    }
}

/// DNS verification status for DKIM, CNAME, DMARC, SPF records.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DnsVerificationStatus {
    Valid,
    Invalid,
    Missing,
    Unverified,
    NotApplicable,
    /// An unknown status not yet covered by this enum.
    #[serde(untagged)]
    Unknown(String),
}

impl std::fmt::Display for DnsVerificationStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Valid => write!(f, "valid"),
            Self::Invalid => write!(f, "invalid"),
            Self::Missing => write!(f, "missing"),
            Self::Unverified => write!(f, "unverified"),
            Self::NotApplicable => write!(f, "not_applicable"),
            Self::Unknown(s) => write!(f, "{s}"),
        }
    }
}

/// DMARC policy value.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DmarcPolicy {
    None,
    Quarantine,
    Reject,
    /// An unknown policy not yet covered by this enum.
    #[serde(untagged)]
    Unknown(String),
}

impl std::fmt::Display for DmarcPolicy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::None => write!(f, "none"),
            Self::Quarantine => write!(f, "quarantine"),
            Self::Reject => write!(f, "reject"),
            Self::Unknown(s) => write!(f, "{s}"),
        }
    }
}

/// Service for the `/domains` endpoints.
#[derive(Clone, Debug)]
pub struct DomainsSvc(pub(crate) Arc<Config>);

impl DomainsSvc {
    /// List all sending domains registered with your account.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let domains = client.domains.list().await?;
    /// for domain in &domains {
    ///     println!("{}: {} (can_send: {})", domain.domain, domain.status, domain.can_send);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn list(&self) -> crate::Result<Vec<Domain>> {
        let request = self.0.build(Method::GET, "/domains");
        let response = self.0.send(request).await?;
        let wrapper = response.json::<ListDomainsResponseWrapper>().await?;
        Ok(wrapper.data.domains)
    }

    /// Register a new sending domain.
    ///
    /// The domain will be created in a pending state until it is verified and approved.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let result = client.domains.create("example.com").await?;
    /// println!("Domain {} created with status: {}", result.domain, result.status);
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn create(&self, domain: &str) -> crate::Result<CreateDomainResponse> {
        let body = CreateDomainRequest {
            domain: domain.to_owned(),
        };
        let request = self.0.build(Method::POST, "/domains").json(&body);
        let response = self.0.send(request).await?;
        let wrapper = response.json::<CreateDomainResponseWrapper>().await?;
        Ok(wrapper.data)
    }

    /// Retrieve details of a single sending domain.
    ///
    /// Returns DNS records, tracking domain configuration, and verification status.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let domain = client.domains.get("example.com").await?;
    /// println!("Status: {}, DKIM: {:?}", domain.status, domain.dkim_status);
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn get(&self, domain: &str) -> crate::Result<DomainDetail> {
        let path = format!("/domains/{domain}");
        let request = self.0.build(Method::GET, &path);
        let response = self.0.send(request).await?;
        let wrapper = response.json::<ShowDomainResponseWrapper>().await?;
        Ok(wrapper.data)
    }

    /// Delete a sending domain.
    ///
    /// The domain will no longer be available for sending emails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// client.domains.delete("example.com").await?;
    /// println!("Domain deleted.");
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn delete(&self, domain: &str) -> crate::Result<()> {
        let path = format!("/domains/{domain}");
        let request = self.0.build(Method::DELETE, &path);
        self.0.send(request).await?;
        Ok(())
    }

    /// Verify a domain's DNS configuration.
    ///
    /// Triggers a DNS lookup to verify DKIM, CNAME, DMARC, and SPF records.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let result = client.domains.verify("example.com").await?;
    /// println!("DKIM: {}, CNAME: {}", result.dkim_status, result.cname_status);
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn verify(&self, domain: &str) -> crate::Result<VerifyDomainResponse> {
        let path = format!("/domains/{domain}/verify");
        let request = self.0.build(Method::POST, &path);
        let response = self.0.send(request).await?;
        let wrapper = response.json::<VerifyDomainResponseWrapper>().await?;
        Ok(wrapper.data)
    }
}

// ── Request Types ──────────────────────────────────────────────────────────

#[derive(Debug, Serialize)]
struct CreateDomainRequest {
    domain: String,
}

// ── Response Types ─────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct ListDomainsResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: ListDomainsData,
}

#[derive(Debug, Deserialize)]
struct ListDomainsData {
    domains: Vec<Domain>,
}

/// A sending domain.
#[derive(Debug, Clone, Deserialize)]
pub struct Domain {
    /// Domain name.
    pub domain: String,
    /// Domain status.
    pub status: DomainStatus,
    /// Human-readable status label.
    pub status_label: String,
    /// Whether this domain can currently send emails.
    pub can_send: bool,
    /// CNAME record verification status.
    pub cname_status: Option<DnsVerificationStatus>,
    /// DKIM record verification status.
    pub dkim_status: Option<DnsVerificationStatus>,
    /// Creation timestamp.
    pub created_at: String,
    /// Last update timestamp.
    pub updated_at: String,
}

#[derive(Debug, Deserialize)]
struct CreateDomainResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: CreateDomainResponse,
}

/// Response from creating a new domain.
#[derive(Debug, Clone, Deserialize)]
pub struct CreateDomainResponse {
    /// Domain name.
    pub domain: String,
    /// Initial domain status.
    pub status: DomainStatus,
    /// Human-readable status label.
    pub status_label: String,
    /// DKIM configuration.
    pub dkim: Option<DkimInfo>,
}

/// DKIM signing information for a domain.
#[derive(Debug, Clone, Deserialize)]
pub struct DkimInfo {
    /// DKIM public key.
    pub public: String,
    /// DKIM selector.
    pub selector: String,
    /// DKIM headers configuration.
    pub headers: String,
    /// Domain used for DKIM signing.
    #[serde(default)]
    pub signing_domain: Option<String>,
}

#[derive(Debug, Deserialize)]
struct ShowDomainResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: DomainDetail,
}

/// Detailed domain information including DNS records.
#[derive(Debug, Clone, Deserialize)]
pub struct DomainDetail {
    /// Domain name.
    pub domain: String,
    /// Domain status.
    pub status: DomainStatus,
    /// Human-readable status label.
    pub status_label: String,
    /// Whether this domain can currently send emails.
    pub can_send: bool,
    /// CNAME record verification status.
    pub cname_status: Option<DnsVerificationStatus>,
    /// DKIM record verification status.
    pub dkim_status: Option<DnsVerificationStatus>,
    /// DMARC verification status.
    #[serde(default)]
    pub dmarc_status: Option<DnsVerificationStatus>,
    /// SPF verification status.
    #[serde(default)]
    pub spf_status: Option<DnsVerificationStatus>,
    /// Whether this is a primary (apex) sending domain.
    #[serde(default)]
    pub is_primary_domain: bool,
    /// Tracking domain, if configured.
    pub tracking_domain: Option<String>,
    /// DNS records for domain verification.
    pub dns: Option<DnsRecords>,
    /// Detected DNS provider.
    #[serde(default)]
    pub dns_provider: Option<DnsProvider>,
    /// Creation timestamp.
    pub created_at: String,
    /// Last update timestamp.
    pub updated_at: String,
}

/// DNS records for domain verification.
#[derive(Debug, Clone, Deserialize)]
pub struct DnsRecords {
    /// DKIM DNS record information.
    pub dkim: Option<DkimDnsRecord>,
}

/// DKIM DNS record details.
#[derive(Debug, Clone, Deserialize)]
pub struct DkimDnsRecord {
    /// DKIM selector.
    pub selector: String,
    /// DKIM public key.
    pub public: String,
    /// Headers included in DKIM signature.
    #[serde(default)]
    pub headers: Option<String>,
}

/// Detected DNS provider for a domain.
#[derive(Debug, Clone, Deserialize)]
pub struct DnsProvider {
    /// Machine-readable DNS provider identifier.
    pub provider: String,
    /// Human-readable DNS provider name.
    pub provider_label: String,
    /// Nameservers detected for the domain.
    pub nameservers: Vec<String>,
    /// Error message if DNS provider detection failed.
    pub error: Option<String>,
}

// ── Domain Verification Types ──────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct VerifyDomainResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: VerifyDomainResponse,
}

/// Response from verifying a domain's DNS configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct VerifyDomainResponse {
    /// The domain name.
    pub domain: String,
    /// DKIM verification status.
    pub dkim_status: DnsVerificationStatus,
    /// CNAME verification status.
    pub cname_status: DnsVerificationStatus,
    /// DMARC verification status.
    pub dmarc_status: DnsVerificationStatus,
    /// SPF verification status.
    pub spf_status: DnsVerificationStatus,
    /// Whether this is a primary (apex) sending domain.
    pub is_primary_domain: bool,
    /// Whether domain ownership has been verified.
    #[serde(default)]
    pub ownership_verified: Option<String>,
    /// DNS verification details.
    #[serde(default)]
    pub dns: Option<DomainDnsVerification>,
    /// DMARC validation result.
    #[serde(default)]
    pub dmarc: Option<DmarcValidationResult>,
    /// SPF validation result.
    #[serde(default)]
    pub spf: Option<SpfValidationResult>,
}

/// DNS verification error details.
#[derive(Debug, Clone, Deserialize)]
pub struct DomainDnsVerification {
    /// Found DKIM record value.
    #[serde(default)]
    pub dkim_record: Option<String>,
    /// Found CNAME record value.
    #[serde(default)]
    pub cname_record: Option<String>,
    /// DKIM verification error message.
    #[serde(default)]
    pub dkim_error: Option<String>,
    /// CNAME verification error message.
    #[serde(default)]
    pub cname_error: Option<String>,
    /// Found DMARC record value.
    #[serde(default)]
    pub dmarc_record: Option<String>,
    /// DMARC verification error message.
    #[serde(default)]
    pub dmarc_error: Option<String>,
    /// Found SPF record value.
    #[serde(default)]
    pub spf_record: Option<String>,
    /// SPF verification error message.
    #[serde(default)]
    pub spf_error: Option<String>,
}

/// DMARC validation result.
#[derive(Debug, Clone, Deserialize)]
pub struct DmarcValidationResult {
    /// Whether a valid DMARC record was found.
    pub is_valid: bool,
    /// DMARC validation status.
    pub status: DnsVerificationStatus,
    /// Domain where the DMARC record was located.
    #[serde(default)]
    pub found_at_domain: Option<String>,
    /// Raw DMARC record value.
    #[serde(default)]
    pub record: Option<String>,
    /// DMARC policy tag (`p=`).
    #[serde(default)]
    pub policy: Option<DmarcPolicy>,
    /// DMARC subdomain policy tag (`sp=`).
    #[serde(default)]
    pub subdomain_policy: Option<DmarcPolicy>,
    /// Validation error message.
    #[serde(default)]
    pub error: Option<String>,
    /// Whether covered by parent domain's subdomain policy.
    pub covered_by_parent_policy: bool,
}

/// SPF validation result.
#[derive(Debug, Clone, Deserialize)]
pub struct SpfValidationResult {
    /// Whether a valid SPF record was found.
    pub is_valid: bool,
    /// SPF validation status.
    pub status: DnsVerificationStatus,
    /// Raw SPF record value.
    #[serde(default)]
    pub record: Option<String>,
    /// Validation error message.
    #[serde(default)]
    pub error: Option<String>,
    /// Whether the SPF record authorises SparkPost.
    pub includes_sparkpost: bool,
}