Skip to main content

serenade_mailer/
address.rs

1//! Email address (mailbox) for Mime.
2
3use std::fmt;
4use std::str::FromStr;
5
6use crate::MailerError;
7
8/// A mailbox: bare address plus optional display name.
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct Address {
11    email: String,
12    name: Option<String>,
13}
14
15impl Address {
16    /// Creates an address with no display name.
17    ///
18    /// # Errors
19    ///
20    /// Returns [`MailerError::InvalidAddress`] when `email` is empty or lacks `@`.
21    pub fn new(email: impl Into<String>) -> Result<Self, MailerError> {
22        Self::with_name(email, None::<String>)
23    }
24
25    /// Creates an address with an optional display name.
26    ///
27    /// # Errors
28    ///
29    /// Returns [`MailerError::InvalidAddress`] when `email` is empty or lacks `@`.
30    pub fn with_name(
31        email: impl Into<String>,
32        name: Option<impl Into<String>>,
33    ) -> Result<Self, MailerError> {
34        let email = email.into().trim().to_owned();
35        validate_email(&email)?;
36        Ok(Self {
37            email,
38            name: name.map(Into::into).filter(|value| !value.is_empty()),
39        })
40    }
41
42    /// Parses `email@host` or `Display Name <email@host>`.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`MailerError::InvalidAddress`] when the mailbox is invalid.
47    pub fn parse(raw: &str) -> Result<Self, MailerError> {
48        let raw = raw.trim();
49        if let Some((name, rest)) = raw.rsplit_once('<')
50            && let Some(email) = rest.strip_suffix('>')
51        {
52            let name = name.trim().trim_matches('"');
53            return Self::with_name(email.trim(), Some(name));
54        }
55        Self::new(raw)
56    }
57
58    /// Parses a comma-separated list of mailboxes.
59    ///
60    /// # Errors
61    ///
62    /// Returns the first [`MailerError::InvalidAddress`] encountered.
63    pub fn parse_list(raw: &str) -> Result<Vec<Self>, MailerError> {
64        raw.split(',')
65            .map(str::trim)
66            .filter(|part| !part.is_empty())
67            .map(Self::parse)
68            .collect()
69    }
70
71    /// Email address string.
72    #[must_use]
73    pub fn email(&self) -> &str {
74        &self.email
75    }
76
77    /// Optional display name.
78    #[must_use]
79    pub fn name(&self) -> Option<&str> {
80        self.name.as_deref()
81    }
82}
83
84impl fmt::Display for Address {
85    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86        if let Some(name) = self.name() {
87            write!(formatter, "{name} <{}>", self.email)
88        } else {
89            write!(formatter, "{}", self.email)
90        }
91    }
92}
93
94impl FromStr for Address {
95    type Err = MailerError;
96
97    fn from_str(value: &str) -> Result<Self, Self::Err> {
98        Self::parse(value)
99    }
100}
101
102impl TryFrom<&str> for Address {
103    type Error = MailerError;
104
105    fn try_from(value: &str) -> Result<Self, Self::Error> {
106        value.parse()
107    }
108}
109
110fn validate_email(email: &str) -> Result<(), MailerError> {
111    if email.is_empty() || !email.contains('@') || email.starts_with('@') || email.ends_with('@') {
112        return Err(MailerError::InvalidAddress {
113            message: format!("invalid email address: {email}"),
114        });
115    }
116    Ok(())
117}