missive 0.7.0

Compose, deliver, preview, and test emails in Rust - pluggable providers with zero configuration code
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
//! Resend API provider.
//!
//! # Example
//!
//! ```rust,ignore
//! use missive::providers::ResendMailer;
//!
//! let mailer = ResendMailer::new("re_xxxxx");
//! ```
//!
//! ## Provider Options
//!
//! Resend-specific options should be set via [`ResendEmailExt`]:
//!
//! ```rust,ignore
//! use chrono::Utc;
//! use missive::providers::ResendEmailExt;
//!
//! let email = Email::new()
//!     .from("sender@example.com")
//!     .to("recipient@example.com")
//!     .subject("Hello")
//!     .resend_tag("category", "welcome")
//!     .resend_scheduled_at(Utc::now())
//!     .resend_idempotency_key("unique-key-123");
//! ```
//!
//! ## Template Support
//!
//! Send emails using Resend templates:
//!
//! ```rust,ignore
//! // Template without variables
//! let email = Email::new()
//!     .from("sender@example.com")
//!     .to("recipient@example.com")
//!     .provider_option("template", json!({"id": "welcome-template"}));
//!
//! // Template with variables
//! let email = Email::new()
//!     .from("sender@example.com")
//!     .to("recipient@example.com")
//!     .provider_option("template", json!({
//!         "id": "welcome-template",
//!         "variables": {
//!             "name": "John",
//!             "action_url": "https://example.com/activate"
//!         }
//!     }));
//! ```

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::email::{Email, PreparedEmail};
use crate::error::MailError;
use crate::mailer::{DeliveryResult, Mailer};

const RESEND_API_URL: &str = "https://api.resend.com";

/// Resend API email provider.
#[must_use = "ResendMailer configuration methods return a modified mailer; chain or assign the returned value"]
pub struct ResendMailer {
    api_key: String,
    client: Client,
    base_url: String,
}

/// Typed extension methods for Resend-specific email options.
pub trait ResendEmailExt: Sized {
    /// Add a Resend analytics tag.
    #[must_use = "resend_tag returns a modified email; chain or assign the returned value"]
    fn resend_tag<N, V>(self, name: N, value: V) -> Self
    where
        N: Into<String>,
        V: Into<String>;

    /// Schedule a Resend email for a future time.
    #[must_use = "resend_scheduled_at returns a modified email; chain or assign the returned value"]
    fn resend_scheduled_at(self, scheduled_at: DateTime<Utc>) -> Self;

    /// Set the Resend idempotency key request header.
    #[must_use = "resend_idempotency_key returns a modified email; chain or assign the returned value"]
    fn resend_idempotency_key<K>(self, key: K) -> Self
    where
        K: Into<String>;

    /// Set a Resend template payload.
    #[must_use = "resend_template returns a modified email; chain or assign the returned value"]
    fn resend_template<T>(self, template: T) -> Result<Self, MailError>
    where
        T: Serialize;
}

impl ResendEmailExt for Email {
    fn resend_tag<N, V>(mut self, name: N, value: V) -> Self
    where
        N: Into<String>,
        V: Into<String>,
    {
        let tag = serde_json::json!({
            "name": name.into(),
            "value": value.into(),
        });

        match self.provider_options.get_mut("tags") {
            Some(Value::Array(tags)) => tags.push(tag),
            _ => {
                self.provider_options
                    .insert("tags".to_string(), Value::Array(vec![tag]));
            }
        }
        self
    }

    fn resend_scheduled_at(mut self, scheduled_at: DateTime<Utc>) -> Self {
        self.provider_options.insert(
            "scheduled_at".to_string(),
            Value::String(scheduled_at.to_rfc3339()),
        );
        self
    }

    fn resend_idempotency_key<K>(mut self, key: K) -> Self
    where
        K: Into<String>,
    {
        self.provider_options
            .insert("idempotency_key".to_string(), Value::String(key.into()));
        self
    }

    fn resend_template<T>(mut self, template: T) -> Result<Self, MailError>
    where
        T: Serialize,
    {
        self.provider_options
            .insert("template".to_string(), serde_json::to_value(template)?);
        Ok(self)
    }
}

impl ResendMailer {
    /// Create a new Resend mailer with the given API key.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            client: Client::new(),
            base_url: RESEND_API_URL.to_string(),
        }
    }

    /// Create with a custom reqwest client.
    pub fn with_client(api_key: impl Into<String>, client: Client) -> Self {
        Self {
            api_key: api_key.into(),
            client,
            base_url: RESEND_API_URL.to_string(),
        }
    }

    /// Set a custom base URL (for testing).
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    async fn build_request(&self, email: &Email) -> Result<ResendRequest, MailError> {
        let from = email.from.as_ref().ok_or(MailError::MissingField("from"))?;

        if email.to.is_empty() {
            return Err(MailError::MissingField("to"));
        }

        let mut request = ResendRequest {
            from: from.formatted_rfc5322_ascii()?,
            to: email
                .to
                .iter()
                .map(|a| a.formatted_rfc5322_ascii())
                .collect::<Result<_, _>>()?,
            subject: if email.subject.is_empty() {
                None
            } else {
                Some(email.subject.clone())
            },
            html: email.html_body.clone(),
            text: email.text_body.clone(),
            cc: if email.cc.is_empty() {
                None
            } else {
                Some(
                    email
                        .cc
                        .iter()
                        .map(|a| a.formatted_rfc5322_ascii())
                        .collect::<Result<_, _>>()?,
                )
            },
            bcc: if email.bcc.is_empty() {
                None
            } else {
                Some(
                    email
                        .bcc
                        .iter()
                        .map(|a| a.formatted_rfc5322_ascii())
                        .collect::<Result<_, _>>()?,
                )
            },
            reply_to: email
                .reply_to
                .first()
                .map(|a| a.formatted_rfc5322_ascii())
                .transpose()?,
            headers: if email.headers.is_empty() {
                None
            } else {
                Some(
                    email
                        .headers
                        .iter()
                        .map(|(k, v)| ResendHeader {
                            name: k.clone(),
                            value: v.clone(),
                        })
                        .collect(),
                )
            },
            attachments: None,
            tags: None,
            scheduled_at: None,
            template: None,
        };

        // Add attachments
        if !email.attachments.is_empty() {
            let mut attachments = Vec::with_capacity(email.attachments.len());
            for a in &email.attachments {
                // Only include content_id for inline attachments
                let content_id = if a.is_inline() {
                    a.content_id.clone()
                } else {
                    None
                };
                attachments.push(ResendAttachment {
                    filename: a.filename.clone(),
                    content: a.base64_data_async().await?,
                    content_type: Some(a.content_type.clone()),
                    content_id,
                });
            }
            request.attachments = Some(attachments);
        }

        // Add provider-specific options
        if let Some(tags) = email.provider_options.get("tags") {
            request.tags = serde_json::from_value(tags.clone()).ok();
        }
        if let Some(scheduled_at) = email.provider_options.get("scheduled_at") {
            request.scheduled_at = scheduled_at.as_str().map(|s| s.to_string());
        }
        if let Some(template) = email.provider_options.get("template") {
            request.template = Some(template.clone());
        }

        Ok(request)
    }
}

#[cfg_attr(
    all(target_family = "wasm", target_os = "unknown"),
    async_trait(?Send)
)]
#[cfg_attr(not(all(target_family = "wasm", target_os = "unknown")), async_trait)]
impl Mailer for ResendMailer {
    async fn deliver_prepared(&self, email: &PreparedEmail) -> Result<DeliveryResult, MailError> {
        let request = self.build_request(email).await?;

        let url = format!("{}/emails", self.base_url);
        let mut req = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .header("User-Agent", format!("missive/{}", crate::VERSION));

        // Add idempotency key header if provided
        if let Some(idempotency_key) = email.provider_options.get("idempotency_key") {
            if let Some(key) = idempotency_key.as_str() {
                req = req.header("Idempotency-Key", key);
            }
        }

        let response = req.json(&request).send().await?;

        let status = response.status();

        if status.is_success() {
            let result: ResendResponse = response.json().await?;
            Ok(DeliveryResult::with_response(
                result.id,
                serde_json::json!({ "provider": "resend" }),
            ))
        } else {
            let error: ResendError = response.json().await.unwrap_or_else(|_| ResendError {
                message: "Unknown error".to_string(),
                name: None,
            });
            Err(MailError::provider_with_status(
                "resend",
                error.message,
                status.as_u16(),
            ))
        }
    }

    /// Validate emails for Resend batch API limitations.
    ///
    /// Resend's batch API does not support:
    /// - `scheduled_at` option
    /// - Attachments
    fn validate_batch(&self, emails: &[PreparedEmail]) -> Result<(), MailError> {
        for (i, email) in emails.iter().enumerate() {
            if email.provider_options.contains_key("scheduled_at") {
                return Err(MailError::UnsupportedFeature(format!(
                    "scheduled_at is not supported in batch sends (email {})",
                    i + 1
                )));
            }
            if !email.attachments.is_empty() {
                return Err(MailError::UnsupportedFeature(format!(
                    "attachments are not supported in Resend batch sends (email {})",
                    i + 1
                )));
            }
        }
        Ok(())
    }

    async fn deliver_many_prepared(
        &self,
        emails: &[PreparedEmail],
    ) -> Result<Vec<DeliveryResult>, MailError> {
        if emails.is_empty() {
            return Ok(vec![]);
        }

        // Validate batch restrictions
        self.validate_batch(emails)?;

        // Build requests
        let mut requests = Vec::with_capacity(emails.len());
        for email in emails {
            requests.push(self.build_request(email).await?);
        }

        let url = format!("{}/emails/batch", self.base_url);
        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .header("User-Agent", format!("missive/{}", crate::VERSION))
            .json(&requests)
            .send()
            .await?;

        let status = response.status();

        if status.is_success() {
            let result: ResendBatchResponse = response.json().await?;
            Ok(result
                .data
                .into_iter()
                .map(|r| {
                    DeliveryResult::with_response(r.id, serde_json::json!({ "provider": "resend" }))
                })
                .collect())
        } else {
            let error: ResendError = response.json().await.unwrap_or_else(|_| ResendError {
                message: "Unknown error".to_string(),
                name: None,
            });
            Err(MailError::provider_with_status(
                "resend",
                error.message,
                status.as_u16(),
            ))
        }
    }

    fn provider_name(&self) -> &'static str {
        "resend"
    }
}

// ============================================================================
// Resend API Types
// ============================================================================

#[derive(Debug, Serialize)]
struct ResendRequest {
    from: String,
    to: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    subject: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    html: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    cc: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    bcc: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    reply_to: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    headers: Option<Vec<ResendHeader>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    attachments: Option<Vec<ResendAttachment>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tags: Option<Vec<ResendTag>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    scheduled_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    template: Option<Value>,
}

#[derive(Debug, Serialize)]
struct ResendHeader {
    name: String,
    value: String,
}

#[derive(Debug, Serialize)]
struct ResendAttachment {
    filename: String,
    content: String, // Base64 encoded
    #[serde(skip_serializing_if = "Option::is_none")]
    content_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    content_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResendTag {
    pub name: String,
    pub value: String,
}

#[derive(Debug, Deserialize)]
struct ResendResponse {
    id: String,
}

#[derive(Debug, Deserialize)]
struct ResendBatchResponse {
    data: Vec<ResendResponse>,
}

#[derive(Debug, Deserialize)]
struct ResendError {
    message: String,
    #[serde(default)]
    #[allow(dead_code)]
    name: Option<String>,
}