azure_functions/send_grid/
email_address.rs

1use serde::{Deserialize, Serialize};
2
3/// Represents an email address containing the email address and name of the sender or recipient.
4#[derive(Debug, Default, Clone, Serialize, Deserialize)]
5pub struct EmailAddress {
6    /// The email address of the sender or recipient.
7    pub email: String,
8    /// The name of the sender or recipient.
9    #[serde(skip_serializing_if = "Option::is_none")]
10    pub name: Option<String>,
11}
12
13impl EmailAddress {
14    /// Creates a new email address.
15    ///
16    /// # Examples
17    ///
18    /// ```rust
19    /// # use azure_functions::send_grid::EmailAddress;
20    /// let address = EmailAddress::new("foo@example.com");
21    /// assert_eq!(address.email, "foo@example.com");
22    /// assert_eq!(address.name, None);
23    /// ```
24    pub fn new<T>(email: T) -> EmailAddress
25    where
26        T: Into<String>,
27    {
28        EmailAddress {
29            email: email.into(),
30            name: None,
31        }
32    }
33
34    /// Creates a new email address with the given name.
35    ///
36    /// # Examples
37    ///
38    /// ```rust
39    /// # use azure_functions::send_grid::EmailAddress;
40    /// let address = EmailAddress::new_with_name("foo@example.com", "Peter");
41    /// assert_eq!(address.email, "foo@example.com");
42    /// assert_eq!(address.name, Some("Peter".to_string()));
43    /// ```
44    pub fn new_with_name<T, U>(email: T, name: U) -> EmailAddress
45    where
46        T: Into<String>,
47        U: Into<String>,
48    {
49        EmailAddress {
50            email: email.into(),
51            name: Some(name.into()),
52        }
53    }
54}
55
56impl<T> From<T> for EmailAddress
57where
58    T: Into<String>,
59{
60    fn from(email: T) -> Self {
61        EmailAddress::new(email)
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    use serde_json::to_string;
69
70    #[test]
71    fn it_serializes_to_json() {
72        let json = to_string(&EmailAddress {
73            email: "foo@example.com".to_owned(),
74            name: None,
75        })
76        .unwrap();
77
78        assert_eq!(json, r#"{"email":"foo@example.com"}"#);
79
80        let json = to_string(&EmailAddress {
81            email: "foo@example.com".to_owned(),
82            name: Some("Foo Example".to_owned()),
83        })
84        .unwrap();
85
86        assert_eq!(json, r#"{"email":"foo@example.com","name":"Foo Example"}"#);
87    }
88
89    #[test]
90    fn it_converts_from_string() {
91        let address: EmailAddress = "foo@example.com".into();
92
93        assert_eq!(address.email, "foo@example.com");
94        assert_eq!(address.name, None);
95    }
96}