resend-rs 0.23.0

Resend's Official Rust SDK.
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
use std::sync::Arc;

use reqwest::Method;

use crate::{
    Config, Result,
    list_opts::{ListOptions, ListResponse},
    types::{
        Automation, AutomationMinimal, AutomationRun, CreateAutomationOptions,
        CreateAutomationResponse, DeleteAutomationResponse, StopAutomationResponse,
        UpdateAutomationOptions, UpdateAutomationResponse,
    },
};

/// `Resend` APIs for `/automations` endpoints.
#[derive(Clone, Debug)]
pub struct AutomationsSvc(pub(crate) Arc<Config>);

impl AutomationsSvc {
    /// Create a new automation to automate email sequences.
    ///
    /// <https://resend.com/docs/api-reference/automations/create-automation>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn create(
        &self,
        automation: CreateAutomationOptions,
    ) -> Result<CreateAutomationResponse> {
        let request = self.0.build(Method::POST, "/automations");
        let response = self.0.send(request.json(&automation)).await?;
        let content = response.json::<CreateAutomationResponse>().await?;

        Ok(content)
    }

    /// Update an existing automation.
    ///
    /// <https://resend.com/docs/api-reference/automations/update-automation>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn update(
        &self,
        automation_id: &str,
        update: UpdateAutomationOptions,
    ) -> Result<UpdateAutomationResponse> {
        let path = format!("/automations/{automation_id}");

        let request = self.0.build(Method::PATCH, &path);
        let response = self.0.send(request.json(&update)).await?;
        let content = response.json::<UpdateAutomationResponse>().await?;

        Ok(content)
    }

    /// Retrieve a single automation.
    ///
    /// <https://resend.com/docs/api-reference/automations/get-automation>
    #[maybe_async::maybe_async]
    pub async fn get(&self, automation_id: &str) -> Result<Automation> {
        let path = format!("/automations/{automation_id}");

        let request = self.0.build(Method::GET, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<Automation>().await?;

        Ok(content)
    }

    /// Retrieve a list of automations.
    ///
    /// <https://resend.com/docs/api-reference/automations/list-automations>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn list<T>(
        &self,
        list_opts: ListOptions<T>,
    ) -> Result<ListResponse<AutomationMinimal>> {
        let request = self.0.build(Method::GET, "/automations").query(&list_opts);
        let response = self.0.send(request).await?;
        let content = response.json::<ListResponse<AutomationMinimal>>().await?;

        Ok(content)
    }

    /// Stop a running automation.
    ///
    /// <https://resend.com/docs/api-reference/automations/stop-automation>
    #[maybe_async::maybe_async]
    pub async fn stop(&self, automation_id: &str) -> Result<StopAutomationResponse> {
        let path = format!("/automations/{automation_id}/stop");

        let request = self.0.build(Method::POST, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<StopAutomationResponse>().await?;

        Ok(content)
    }

    /// Remove an existing automation.
    ///
    /// <https://resend.com/docs/api-reference/automations/delete-automation>
    #[maybe_async::maybe_async]
    pub async fn delete(&self, automation_id: &str) -> Result<DeleteAutomationResponse> {
        let path = format!("/automations/{automation_id}");

        let request = self.0.build(Method::DELETE, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<DeleteAutomationResponse>().await?;

        Ok(content)
    }

    /// Retrieve a list of automation runs.
    ///
    /// <https://resend.com/docs/api-reference/automations/list-automation-runs>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn list_runs<T>(
        &self,
        automation_id: &str,
        status_filter: Option<String>,
        list_opts: ListOptions<T>,
    ) -> Result<ListResponse<AutomationRun>> {
        let path = format!("/automations/{automation_id}/runs");

        let request = self
            .0
            .build(Method::GET, &path)
            .query(&list_opts)
            .query(&status_filter);
        let response = self.0.send(request).await?;
        let content = response.json::<ListResponse<AutomationRun>>().await?;

        Ok(content)
    }

    /// Retrieve a single automation run.
    ///
    /// <https://resend.com/docs/api-reference/automations/get-automation-run>
    #[maybe_async::maybe_async]
    pub async fn get_run(&self, automation_id: &str, run_id: &str) -> Result<AutomationRun> {
        let path = format!("/automations/{automation_id}/runs/{run_id}");

        let request = self.0.build(Method::GET, &path);
        let response = self.0.send(request).await?;
        let content = response.json::<AutomationRun>().await?;

        Ok(content)
    }
}

#[allow(unreachable_pub)]
pub mod types {
    use std::collections::HashMap;

    use serde::{Deserialize, Serialize};
    use serde_json::Value;

    crate::define_id_type!(AutomationId);
    crate::define_id_type!(AutomationRunId);

    #[must_use]
    #[derive(Debug, Clone, Serialize)]
    pub struct CreateAutomationOptions {
        pub name: String,
        pub status: AutomationStatus,
        pub steps: Vec<Step>,
        pub connections: Vec<Connection>,
    }

    #[must_use]
    #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
    #[serde(rename_all = "snake_case")]
    pub enum AutomationStatus {
        Enabled,
        #[default]
        Disabled,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(tag = "type", rename_all = "snake_case")]
    pub enum Step {
        Trigger {
            key: String,
            config: TriggerStepConfig,
        },
        SendEmail {
            key: String,
            config: SendEmailStepConfig,
        },
        Delay {
            key: String,
            config: DelayStepConfig,
        },
        WaitForEvent {
            key: String,
            config: WaitForEventStepConfig,
        },
        Condition {
            key: String,
            config: Value,
        },
        ContactUpdate {
            key: String,
            config: Value,
        },
        ContactDelete {
            key: String,
            config: Value,
        },
        AddToSegment {
            key: String,
            config: AddToSegmentStepConfig,
        },
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct TriggerStepConfig {
        pub event_name: String,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct SendEmailStepConfig {
        pub template: AutomationTemplate,
        pub subject: Option<String>,
        pub from: Option<String>,
        pub reply_to: Option<String>,
        pub variables: Option<Value>,
    }

    impl SendEmailStepConfig {
        #[inline]
        pub fn new(template: AutomationTemplate) -> Self {
            Self {
                template,
                subject: None,
                from: None,
                reply_to: None,
                variables: None,
            }
        }

        #[inline]
        pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
            self.subject = Some(subject.into());
            self
        }

        #[inline]
        pub fn with_from(mut self, from: impl Into<String>) -> Self {
            self.from = Some(from.into());
            self
        }

        #[inline]
        pub fn with_reply_to(mut self, reply_to: impl Into<String>) -> Self {
            self.reply_to = Some(reply_to.into());
            self
        }

        #[inline]
        pub fn with_variables(mut self, variables: Value) -> Self {
            self.variables = Some(variables);
            self
        }
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    pub struct AutomationTemplate {
        pub id: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub variables: Option<Value>,
    }

    impl AutomationTemplate {
        #[inline]
        pub fn new(id: impl Into<String>) -> Self {
            Self {
                id: id.into(),
                variables: None,
            }
        }

        #[inline]
        pub fn with_variables(mut self, variables: Value) -> Self {
            self.variables = Some(variables);
            self
        }
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct DelayStepConfig {
        pub duration: String,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct WaitForEventStepConfig {
        pub event_name: String,
        pub timeout: Option<String>,
        pub filter_rule: Option<Value>,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct AddToSegmentStepConfig {
        pub segment_id: String,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct Connection {
        pub from: String,
        pub to: String,
        pub r#type: Option<ConnectionType>,
    }

    impl Connection {
        #[inline]
        pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
            Self {
                from: from.into(),
                to: to.into(),
                r#type: None,
            }
        }

        #[inline]
        pub fn with_type(mut self, r#type: ConnectionType) -> Self {
            self.r#type = Some(r#type);
            self
        }
    }

    #[must_use]
    #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
    #[serde(rename_all = "snake_case")]
    pub enum ConnectionType {
        #[default]
        Default,
        ConditionMet,
        ConditionNotMet,
        Timeout,
        EventReceived,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct CreateAutomationResponse {
        pub id: AutomationId,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct Automation {
        pub id: AutomationId,
        pub name: String,
        pub status: AutomationStatus,
        pub created_at: String,
        pub updated_at: Option<String>,
        pub steps: Vec<Step>,
        pub connections: Vec<Connection>,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct AutomationMinimal {
        pub id: AutomationId,
        pub name: String,
        pub status: AutomationStatus,
        pub created_at: String,
        pub updated_at: Option<String>,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Default)]
    pub struct UpdateAutomationOptions {
        #[serde(skip_serializing_if = "Option::is_none")]
        name: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        status: Option<AutomationStatus>,
        #[serde(skip_serializing_if = "Option::is_none")]
        steps: Option<Vec<Step>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        connections: Option<Vec<Connection>>,
    }

    impl UpdateAutomationOptions {
        #[inline]
        pub fn new() -> Self {
            Self::default()
        }

        #[inline]
        pub fn with_name(mut self, name: &str) -> Self {
            self.name = Some(name.to_owned());
            self
        }

        #[inline]
        pub fn with_status(mut self, status: AutomationStatus) -> Self {
            self.status = Some(status);
            self
        }

        #[inline]
        pub fn with_steps(mut self, steps: Vec<Step>) -> Self {
            self.steps = Some(steps);
            self
        }

        #[inline]
        pub fn with_connections(mut self, connections: Vec<Connection>) -> Self {
            self.connections = Some(connections);
            self
        }
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct UpdateAutomationResponse {
        pub id: AutomationId,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct StopAutomationResponse {
        pub id: AutomationId,
        pub status: AutomationStatus,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct DeleteAutomationResponse {
        pub id: AutomationId,
        pub deleted: bool,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct AutomationRun {
        id: AutomationRunId,
        #[serde(skip_serializing_if = "Option::is_none")]
        started_at: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        completed_at: Option<String>,
        created_at: String,
        status: AutomationRunStatus,
        trigger: Option<AutomationRunTrigger>,
    }

    #[must_use]
    #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum AutomationRunStatus {
        Running,
        Completed,
        Failed,
        Cancelled,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct AutomationRunTrigger {
        event_name: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        payload: Option<HashMap<String, Value>>,
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(clippy::needless_return)]
mod test {
    use crate::{
        automations::types::{SendEmailStepConfig, TriggerStepConfig},
        test::{CLIENT, DebugResult},
        types::{Automation, AutomationStatus, Connection, CreateAutomationOptions, Step},
    };

    #[test]
    fn serialize_create() {
        let tmp = CreateAutomationOptions {
            name: "Welcome series".to_owned(),
            status: AutomationStatus::Enabled,
            steps: vec![
                Step::Trigger {
                    key: "start".to_owned(),
                    config: TriggerStepConfig {
                        event_name: "user.created".to_owned(),
                    },
                },
                Step::SendEmail {
                    key: "welcome".to_owned(),
                    config: SendEmailStepConfig {
                        subject: None,
                        from: None,
                        reply_to: None,
                        variables: None,
                        template: crate::automations::types::AutomationTemplate {
                            id: "34a080c9-b17d-4187-ad80-5af20266e535".to_owned(),
                            variables: None,
                        },
                    },
                },
            ],
            connections: vec![Connection {
                from: "start".to_owned(),
                to: "welcome".to_owned(),
                r#type: None,
            }],
        };

        println!("{}", serde_json::to_string(&tmp).unwrap());
    }

    #[test]
    fn deserialize_get() {
        let tmp = r#"
          {
            "object": "automation",
            "id": "c9b16d4f-ba6c-4e2e-b044-6bf4404e57fd",
            "name": "Welcome series",
            "status": "disabled",
            "created_at": "2026-10-01 12:00:00.000000+00",
            "updated_at": "2026-10-01 12:00:00.000000+00",
            "steps": [
              {
                "key": "start",
                "type": "trigger",
                "config": { "event_name": "user.created" }
              },
              {
                "key": "welcome",
                "type": "send_email",
                "config": {
                  "template": { "id": "34a080c9-b17d-4187-ad80-5af20266e535" }
                }
              }
            ],
            "connections": [
              {
                "from": "start",
                "to": "welcome",
                "type": "default"
              }
            ]
          }"#;

        let _res = serde_json::from_str::<Automation>(tmp).unwrap();
    }

    #[tokio_shared_rt::test(shared = true)]
    #[cfg(not(feature = "blocking"))]
    async fn all() -> DebugResult<()> {
        use crate::{list_opts::ListOptions, types::UpdateAutomationOptions};

        let resend = &*CLIENT;

        // Create
        let opts = CreateAutomationOptions {
            name: "Welcome series".to_owned(),
            status: AutomationStatus::Enabled,
            steps: vec![Step::Trigger {
                key: "trigger".to_owned(),
                config: TriggerStepConfig {
                    event_name: "user.created".to_owned(),
                },
            }],
            connections: vec![],
        };
        let automation = resend.automations.create(opts).await?;
        std::thread::sleep(std::time::Duration::from_secs(2));

        // Update
        let opts = UpdateAutomationOptions::new().with_status(AutomationStatus::Enabled);
        let automation = resend.automations.update(&automation.id, opts).await?;

        // Get
        let automation = resend.automations.get(&automation.id).await?;

        // List
        let automations = resend.automations.list(ListOptions::default()).await?;
        assert!(!automations.data.is_empty());

        // List Runs
        let runs = resend
            .automations
            .list_runs(&automation.id, None, ListOptions::default())
            .await?;
        assert!(runs.data.is_empty());

        // Stop
        let automation = resend.automations.stop(&automation.id).await?;

        std::thread::sleep(std::time::Duration::from_secs(2));

        // Delete
        let automation = resend.automations.delete(&automation.id).await?;
        assert!(automation.deleted);

        Ok(())
    }
}