laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! Someone a message goes to.

use laravel::mail::Address;
use serde::{Deserialize, Serialize};

/// Someone a message can go to. A template type's fields of this type (or `Option<Recipient>`,
/// or `Vec<Recipient>`) are its recipient variables: a template lists them in `to`, `cc` or `bcc`
/// to send to them. Templates read `email`, `name` and `locale` like any other fields.
///
/// ```
/// use laravel_template_engine::Recipient;
///
/// let customer = Recipient::new("olena@example.com").name("Olena").locale("uk");
/// assert_eq!(customer.locale.as_deref(), Some("uk"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Recipient {
    /// The email address.
    pub email: String,
    /// The name shown next to the address.
    #[serde(default)]
    pub name: Option<String>,
    /// The language the recipient reads, such as `uk` or `en-GB`. Messages to them use the
    /// template's text in this language when it has one.
    #[serde(default)]
    pub locale: Option<String>,
}

impl Recipient {
    /// A recipient with only an email address.
    #[must_use]
    pub fn new(email: impl Into<String>) -> Self {
        Self {
            email: email.into(),
            name: None,
            locale: None,
        }
    }

    /// Sets the name.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the language.
    #[must_use]
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = Some(locale.into());
        self
    }

    pub(crate) fn address(&self) -> Address {
        let address = Address::new(self.email.clone());
        match &self.name {
            Some(name) => address.with_name(name.clone()),
            None => address,
        }
    }
}

impl From<&str> for Recipient {
    fn from(email: &str) -> Self {
        Self::new(email)
    }
}

impl From<String> for Recipient {
    fn from(email: String) -> Self {
        Self::new(email)
    }
}