resend-rs 0.24.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
use std::sync::Arc;

use reqwest::Method;
use types::{UpdateBroadcastOptions, UpdateBroadcastResponse};

use crate::{Config, Result, list_opts::ListResponse};
use crate::{
    list_opts::ListOptions,
    types::{
        Broadcast, CreateBroadcastOptions, CreateBroadcastResponse, RemoveBroadcastResponse,
        SendBroadcastOptions, SendBroadcastResponse,
    },
};

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

impl BroadcastsSvc {
    /// Create a new broadcast to send to your audience.
    ///
    /// <https://resend.com/docs/api-reference/broadcasts/create-broadcast>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn create(
        &self,
        broadcast: CreateBroadcastOptions,
    ) -> Result<CreateBroadcastResponse> {
        let request = self.0.build(Method::POST, "/broadcasts");
        let response = self.0.send(request.json(&broadcast)).await?;
        let content = response.json::<CreateBroadcastResponse>().await?;

        Ok(content)
    }

    /// Start sending broadcasts to your audience through the Resend API.
    ///
    /// <https://resend.com/docs/api-reference/broadcasts/send-broadcast>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn send(&self, broadcast: SendBroadcastOptions) -> Result<SendBroadcastResponse> {
        let path = format!("/broadcasts/{}/send", broadcast.broadcast_id);

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

        Ok(content)
    }

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

        Ok(content)
    }

    /// Retrieve a single broadcast.
    ///
    /// <https://resend.com/docs/api-reference/broadcasts/get-broadcast>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn get(&self, broadcast_id: &str) -> Result<Broadcast> {
        let path = format!("/broadcasts/{broadcast_id}");

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

        Ok(content)
    }

    /// Remove an existing broadcast.
    ///
    /// <https://resend.com/docs/api-reference/broadcasts/delete-broadcast>
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn delete(&self, broadcast_id: &str) -> Result<bool> {
        let path = format!("/broadcasts/{broadcast_id}");

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

        Ok(content.deleted)
    }

    /// Update a broadcast to send to your audience.
    #[maybe_async::maybe_async]
    #[allow(clippy::needless_pass_by_value)]
    pub async fn update(
        &self,
        broadcast_id: &str,
        update: UpdateBroadcastOptions,
    ) -> Result<UpdateBroadcastResponse> {
        let path = format!("/broadcasts/{broadcast_id}");

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

        Ok(content)
    }
}

#[allow(unreachable_pub)]
pub mod types {
    use ecow::EcoString;
    use serde::{Deserialize, Serialize};

    use crate::types::SegmentId;

    /// Details of a new `Broadcast`.
    #[must_use]
    #[derive(Debug, Clone, Serialize)]
    pub struct CreateBroadcastOptions {
        audience_id: String,
        from: String,
        subject: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        reply_to: Option<Vec<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")]
        name: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        send: Option<bool>,
        #[serde(skip_serializing_if = "Option::is_none")]
        scheduled_at: Option<String>,
    }

    impl CreateBroadcastOptions {
        /// Creates a new [`CreateBroadcastOptions`].
        ///
        /// - `audience_id`: The ID of the audience you want to send to.
        /// - `from`: To include a friendly name, use the format `"Your Name <sender@domain.com>"`.
        /// - `subject`: Email subject.
        pub fn new(audience_id: &str, from: &str, subject: &str) -> Self {
            Self {
                audience_id: audience_id.to_string(),
                from: from.to_string(),
                subject: subject.to_string(),
                reply_to: None,
                html: None,
                text: None,
                name: None,
                send: None,
                scheduled_at: None,
            }
        }

        /// Appends `reply_to` address to the broadcast.
        #[inline]
        pub fn with_reply(mut self, to: &str) -> Self {
            let reply_to = self.reply_to.get_or_insert_with(Vec::new);
            reply_to.push(to.to_owned());
            self
        }

        /// Appends multiple `reply_to` addresses to the broadcast.
        #[inline]
        pub fn with_reply_multiple(mut self, to: &[String]) -> Self {
            let reply_to = self.reply_to.get_or_insert_with(Vec::new);
            reply_to.extend_from_slice(to);
            self
        }

        /// Adds or overwrites the HTML version of the message.
        #[inline]
        pub fn with_html(mut self, html: &str) -> Self {
            self.html = Some(html.to_owned());
            self
        }

        /// Adds or overwrites the plain text version of the message.
        #[inline]
        pub fn with_text(mut self, text: &str) -> Self {
            self.text = Some(text.to_owned());
            self
        }

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

        /// When set to `true`, the broadcast will be sent or scheduled (if `scheduled_at` is
        /// provided) without requiring a separate call to the
        /// [`crate::broadcasts::BroadcastsSvc::send`] endpoint.
        #[inline]
        pub fn with_send(mut self, send: bool) -> Self {
            self.send = Some(send);
            self
        }

        /// Schedule email to be sent later. The date should be in language natural (e.g.: in 1 min)
        /// or ISO 8601 format (e.g: 2024-08-05T11:52:01.858Z).
        #[inline]
        pub fn with_scheduled_at(mut self, scheduled_at: &str) -> Self {
            self.scheduled_at = Some(scheduled_at.to_owned());
            self
        }
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Default)]
    pub struct UpdateBroadcastOptions {
        #[serde(skip_serializing_if = "Option::is_none")]
        from: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        subject: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        reply_to: Option<Vec<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")]
        name: Option<String>,
    }

    impl UpdateBroadcastOptions {
        /// Creates a new [`UpdateBroadcastOptions`].
        pub fn new() -> Self {
            Self::default()
        }

        /// Adds or overwrites the sender email address.
        #[inline]
        pub fn with_from(mut self, from: &str) -> Self {
            self.from = Some(from.to_owned());
            self
        }

        /// Adds or overwrites the subject.
        #[inline]
        pub fn with_subject(mut self, subject: &str) -> Self {
            self.subject = Some(subject.to_owned());
            self
        }

        /// Appends `reply_to` address to the broadcast.
        pub fn with_reply(mut self, to: &str) -> Self {
            let reply_to = self.reply_to.get_or_insert_with(Vec::new);
            reply_to.push(to.to_owned());
            self
        }

        /// Appends multiple `reply_to` addresses to the broadcast.
        #[inline]
        pub fn with_reply_multiple(mut self, to: &[String]) -> Self {
            let reply_to = self.reply_to.get_or_insert_with(Vec::new);
            reply_to.extend_from_slice(to);
            self
        }

        /// Adds or overwrites the HTML version of the message.
        #[inline]
        pub fn with_html(mut self, html: &str) -> Self {
            self.html = Some(html.to_owned());
            self
        }

        /// Adds or overwrites the plain text version of the message.
        #[inline]
        pub fn with_text(mut self, text: &str) -> Self {
            self.text = Some(text.to_owned());
            self
        }

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

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct UpdateBroadcastResponse {
        /// Unique identifier for the updated broadcast.
        pub id: BroadcastId,
    }

    crate::define_id_type!(BroadcastId);

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct CreateBroadcastResponse {
        /// The ID of the created broadcast.
        pub id: BroadcastId,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize)]
    pub struct SendBroadcastOptions {
        pub(crate) broadcast_id: BroadcastId,

        #[serde(skip_serializing_if = "Option::is_none")]
        scheduled_at: Option<String>,
    }

    impl SendBroadcastOptions {
        pub fn new(broadcast_id: &str) -> Self {
            let broadcast_id = BroadcastId(EcoString::from(broadcast_id.to_owned()));

            Self {
                broadcast_id,
                scheduled_at: None,
            }
        }

        /// Schedule email to be sent later. The date should be in language natural (e.g.: in 1 min)
        /// or ISO 8601 format (e.g: 2024-08-05T11:52:01.858Z).
        #[inline]
        pub fn with_scheduled_at(mut self, scheduled_at: &str) -> Self {
            self.scheduled_at = Some(scheduled_at.to_owned());
            self
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct SendBroadcastResponse {
        /// The ID of the sent broadcast.
        pub id: BroadcastId,
    }

    #[must_use]
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct Broadcast {
        pub id: BroadcastId,
        pub name: String,
        pub audience_id: SegmentId,
        pub status: String,
        pub created_at: String,
        pub scheduled_at: Option<String>,
        pub sent_at: Option<String>,
        pub from: Option<String>,
        pub subject: Option<String>,
        pub reply_to: Option<Vec<String>>,
        pub preview_text: Option<String>,
        pub text: Option<String>,
        pub html: Option<String>,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct RemoveBroadcastResponse {
        /// The ID of the broadcast.
        #[allow(dead_code)]
        pub id: BroadcastId,
        /// The deleted attribute indicates that the corresponding broadcast has been deleted.
        pub deleted: bool,
    }
}

#[cfg(test)]
#[allow(clippy::needless_return, clippy::indexing_slicing)]
mod test {
    use crate::list_opts::ListOptions;
    use crate::{
        test::{CLIENT, DebugResult},
        types::{
            CreateBroadcastOptions, CreateContactOptions, SendBroadcastOptions,
            UpdateBroadcastOptions,
        },
    };

    use super::types::Broadcast;

    #[tokio_shared_rt::test(shared = true)]
    #[cfg(not(feature = "blocking"))]
    #[ignore = "Can no longer send broadcasts from the resend.dev domain"]
    async fn create_send_broadcast() -> DebugResult<()> {
        let resend = &*CLIENT;
        std::thread::sleep(std::time::Duration::from_secs(1));

        let audience_id = resend.segments.create("audience").await?.id;

        let contact = CreateContactOptions::new("steve.wozniak@gmail.com")
            .with_first_name("Steve")
            .with_last_name("Wozniak")
            .with_unsubscribed(false)
            .with_audience_id(&audience_id);

        let _contact_id = resend.contacts.create(contact).await?;

        let from = "Acme <onboarding@resend.dev>";
        let subject = "hello world";
        let html =
            "Hi {{{FIRST_NAME|there}}}, you can unsubscribe here: {{{RESEND_UNSUBSCRIBE_URL}}}";

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

        // Create
        let broadcast = CreateBroadcastOptions::new(&audience_id, from, subject).with_html(html);
        let res = resend.broadcasts.create(broadcast).await?;

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

        // Send
        let opts = SendBroadcastOptions::new(&res.id);
        let _res = resend.broadcasts.send(opts).await?;

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

        let deleted = resend.segments.delete(&audience_id).await?;
        std::thread::sleep(std::time::Duration::from_secs(1));

        assert!(deleted);

        Ok(())
    }

    #[tokio_shared_rt::test(shared = true)]
    #[cfg(not(feature = "blocking"))]
    #[ignore = "Can no longer send broadcasts from the resend.dev domain"]
    async fn list_get_broadcast() -> DebugResult<()> {
        let resend = &*CLIENT;
        std::thread::sleep(std::time::Duration::from_secs(1));

        let broadcasts = resend.broadcasts.list(ListOptions::default()).await?;
        assert!(!broadcasts.data.is_empty(), "No broadcasts found");
        let broadcast = broadcasts[0].clone();

        let _res = resend.broadcasts.get(&broadcast.id.clone()).await?;
        let _deleted = resend.broadcasts.delete(&broadcast.id).await;
        // TODO: This does not seem to be the case anymore?
        // Already used broadcasts cant be deleted
        // assert!(deleted.is_err());

        // Create fresh broadcast and delete that instead
        let audience_id = resend.segments.create("audience").await?.id;
        let from = "Acme <onboarding@resend.dev>";
        let subject = "hello world";
        let text = "text";

        let broadcast = CreateBroadcastOptions::new(&audience_id, from, subject).with_text(text);
        let res = resend.broadcasts.create(broadcast).await?;
        std::thread::sleep(std::time::Duration::from_secs(2));
        let deleted_broadcast = resend.broadcasts.delete(&res.id).await;
        let deleted_audience = resend.segments.delete(&audience_id).await;
        std::thread::sleep(std::time::Duration::from_secs(1));

        assert!(deleted_broadcast.is_ok());
        assert!(deleted_audience.is_ok());

        Ok(())
    }

    #[tokio_shared_rt::test(shared = true)]
    #[cfg(not(feature = "blocking"))]
    #[ignore = "Can no longer send broadcasts from the resend.dev domain"]
    async fn update_broadcast() -> DebugResult<()> {
        let resend = &*CLIENT;
        std::thread::sleep(std::time::Duration::from_secs(1));

        // Create audience & broadcast
        let audience_id = resend.segments.create("audience").await?.id;
        let from = "Acme <onboarding@resend.dev>";
        let subject = "hello world";

        let create_broadcast =
            CreateBroadcastOptions::new(&audience_id, from, subject).with_text("text");
        let broadcast_id = resend.broadcasts.create(create_broadcast).await?.id;
        std::thread::sleep(std::time::Duration::from_secs(2));

        // Assert subject == initial subject
        let broadcast = resend.broadcasts.get(&broadcast_id).await?;
        assert_eq!(Some(subject.to_string()), broadcast.subject);

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

        // Update subject
        let subject = "updated";
        let opts = UpdateBroadcastOptions::new().with_subject(subject);
        let _unused = resend.broadcasts.update(&broadcast_id, opts).await?;

        // Assert subject == updated subject
        let broadcast = resend.broadcasts.get(&broadcast_id).await?;
        assert_eq!(Some(subject.to_string()), broadcast.subject);

        // Delete
        let deleted = resend.broadcasts.delete(&broadcast_id).await?;
        assert!(deleted);

        Ok(())
    }

    #[test]
    fn parse_broadcast_test() {
        let data = r#"{
    "object": "broadcast",
    "id": "498ee8e4-7aa2-4eb5-9f04-4194848049d1",
    "name": "Untitled",
    "audience_id": "fd644f07-a05a-467e-9bae-23bb7c35766a",
    "from": "Acme <onboarding@resend.dev>",
    "subject": "Hello!",
    "reply_to": [],
    "preview_text": null,
    "status": "scheduled",
    "created_at": "2024-12-18 18:05:09.905933+00",
    "scheduled_at": null,
    "sent_at": null
}"#;

        let _parsed = serde_json::from_str::<Broadcast>(data).expect("Parsing failed");
    }
}