Skip to main content

worker/
email.rs

1use futures_util::TryStreamExt;
2use wasm_bindgen::JsCast;
3
4pub use crate::bindings::email::*;
5use crate::{ByteStream, EnvBinding, Result};
6
7impl EnvBinding for SendEmail {
8    const TYPE_NAME: &'static str = "SendEmail";
9
10    // `SendEmail` is a TypeScript interface, not a class — the runtime
11    // doesn't expose a `SendEmail` global for the default
12    // `constructor.name` check to match against. The TS types are
13    // authoritative: if `env.EMAIL` is bound to a SendEmail per
14    // `wrangler.toml`, the runtime hands us the right shape, so we
15    // skip the check and `unchecked_into`.
16    fn get(val: wasm_bindgen::JsValue) -> Result<Self> {
17        Ok(val.unchecked_into())
18    }
19}
20
21impl ForwardableEmailMessage {
22    /// Stream of the raw email content.
23    pub fn raw_byte_stream(&self) -> ByteStream {
24        self.raw().into()
25    }
26
27    /// Convenience: collect the raw email content into a `Vec<u8>`.
28    pub async fn raw_bytes(&self) -> Result<Vec<u8>> {
29        Into::<ByteStream>::into(self.raw())
30            .try_fold(Vec::new(), |mut bytes, mut chunk| async move {
31                bytes.append(&mut chunk);
32                Ok(bytes)
33            })
34            .await
35    }
36}
37
38#[cfg(test)]
39mod send_check {
40    // `SendEmail` and `InboundEmail` are `Send` automatically —
41    // wasm-bindgen makes `JsValue` `Send + Sync` and every extern `pub type`
42    // carries that through. This compile-time check guards against an
43    // upstream regression.
44    use super::{ForwardableEmailMessage, SendEmail};
45    fn _assert_send<T: Send>() {}
46    #[allow(dead_code)]
47    fn _check() {
48        _assert_send::<SendEmail>();
49        _assert_send::<ForwardableEmailMessage>();
50    }
51}