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
//! A library for sending notifications
//! via email. If you need a quick and
//! dirty way to send out notifications
//! (and you have access to an email server),
//! this crate is for you!
use chrono::prelude::*;
use lettre::{
    file::error::FileResult, sendmail::error::SendmailResult, smtp::error::SmtpResult,
    EmailAddress, Envelope, FileTransport, SendableEmail, SmtpTransport, Transport,
};

pub use lettre::smtp::{client::net::ClientTlsParameters, ClientSecurity, SmtpClient};
use std::net::ToSocketAddrs;

mod echo_transport;

#[derive(Debug)]
pub enum Error {
    Lettre(lettre::error::Error),
    LettreFile(lettre::file::error::Error),
    LettreSendMail(lettre::sendmail::error::Error),
    LettreSmtp(lettre::smtp::error::Error),
    Io(std::io::Error),
    MissingEmail,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::Lettre(i) => i.fmt(f),
            Error::LettreFile(i) => i.fmt(f),
            Error::LettreSendMail(i) => i.fmt(f),
            Error::LettreSmtp(i) => i.fmt(f),
            Error::Io(i) => i.fmt(f),
            Error::MissingEmail => write!(f, "Error, email address to build a Sender"),
        }
    }
}

impl std::error::Error for Error {}

impl From<lettre::error::Error> for Error {
    fn from(other: lettre::error::Error) -> Self {
        Self::Lettre(other)
    }
}

impl From<lettre::file::error::Error> for Error {
    fn from(other: lettre::file::error::Error) -> Self {
        Self::LettreFile(other)
    }
}

impl From<lettre::sendmail::error::Error> for Error {
    fn from(other: lettre::sendmail::error::Error) -> Self {
        Self::LettreSendMail(other)
    }
}

impl From<lettre::smtp::error::Error> for Error {
    fn from(other: lettre::smtp::error::Error) -> Self {
        Self::LettreSmtp(other)
    }
}

impl From<std::io::Error> for Error {
    fn from(other: std::io::Error) -> Self {
        Self::Io(other)
    }
}

/// A builder for easily
/// creating a `Sender`
pub struct SenderBuilder {
    pub(crate) address: Option<EmailAddress>,
}

impl SenderBuilder {
    /// Set the address for this sender
    /// to send from.
    ///
    /// > Note: This is required to be used.
    pub fn address(mut self, from: &str) -> Self {
        if let Ok(add) = EmailAddress::new(from.to_string()) {
            self.address = Some(add);
        }
        self
    }

    /// This takes a file path and will write the email
    /// to a file on the file system as json using
    pub fn file<'a, P: AsRef<std::path::Path>>(
        self,
        p: P,
    ) -> Result<Sender<'a, FileResult>, Error> {
        let client = Box::new(FileTransport::new(p));
        if let Some(address) = self.address {
            Ok(Sender { address, client })
        } else {
            Err(Error::MissingEmail)
        }
    }

    /// This uses the `sendmail` cli tool for sending an email
    pub fn sendmail<'a>(self) -> Result<Sender<'a, SendmailResult>, Error> {
        let client = Box::new(lettre::SendmailTransport::new());
        if let Some(address) = self.address {
            Ok(Sender { address, client })
        } else {
            Err(Error::MissingEmail)
        }
    }
    /// Unencrypted Localhost, this is by far the simplest, but least secure
    pub fn smtp_unencrypted_localhost<'a>(self) -> Result<Sender<'a, SmtpResult>, Error> {
        let smtp = lettre::SmtpClient::new_unencrypted_localhost()?;
        self.smtp(smtp)
    }

    /// You provide a domain (as an `&str`) and it will use TLS to send the message
    pub fn smtp_simple<'a>(self, domain: &str) -> Result<Sender<'a, SmtpResult>, Error> {
        let smtp = lettre::SmtpClient::new_simple(domain)?;
        self.smtp(smtp)
    }
    /// You provide the socket address and security
    /// see [the lettre documentation to learn more](https://docs.rs/lettre/0.9.2/lettre/smtp/enum.ClientSecurity.html)
    pub fn smtp_full<'a, A: ToSocketAddrs>(
        self,
        addr: A,
        security: ClientSecurity,
    ) -> Result<Sender<'a, SmtpResult>, Error> {
        let smtp = SmtpClient::new(addr, security)?;
        self.smtp(smtp)
    }

    /// The most manual method, you need to provide
    /// the fully constructed client
    /// see [the lettre documentation to learn more](https://docs.rs/lettre/0.9.2/lettre/smtp/struct.SmtpClient.html)
    pub fn smtp<'a>(self, smtp: SmtpClient) -> Result<Sender<'a, SmtpResult>, Error> {
        let client = Box::new(SmtpTransport::new(smtp));
        if let Some(address) = self.address {
            Ok(Sender { address, client })
        } else {
            Err(Error::MissingEmail)
        }
    }

    pub fn stdout<'a>(self) -> Result<Sender<'a, std::io::Result<()>>, Error> {
        let client = Box::new(echo_transport::EchoTransport);
        if let Some(address) = self.address {
            Ok(Sender { address, client })
        } else {
            Err(Error::MissingEmail)
        }
    }
}

pub struct Sender<'a, R> {
    pub address: EmailAddress,
    pub client: Box<dyn Transport<'a, Result = R>>,
}

impl<'a> Sender<'a, ()> {
    pub fn builder() -> SenderBuilder {
        SenderBuilder { address: None }
    }
}

impl<'a, R, E> Sender<'a, Result<R, E>>
where
    E: Into<Error>,
{
    pub fn send_to(&mut self, dest: &Destination, msg: &str) -> Result<R, Error> {
        let to = EmailAddress::new(dest.address())?;
        let from = self.address.clone();
        let env = Envelope::new(Some(from), vec![to])?;
        let email = SendableEmail::new(env, Utc::now().to_rfc2822(), msg.as_bytes().to_vec());
        match self.client.send(email) {
            Ok(r) => Ok(r),
            Err(e) => Err(e.into()),
        }
    }
}

/// A cell phone carrier
///
/// > Note: this is currently only US providers
/// > with support, we could include others as
/// > well. The `Other` case will allow for
/// > you to extend this enum with anything
/// > not currently provided
#[derive(Debug, Clone)]
pub enum Carrier {
    /// [number]@txt.att.net
    ATT,
    /// [number]@messaging.sprintpcs.com
    Sprint,
    /// [number]@tmomail.net
    TMobile,
    /// [number]@vtext.com
    Verizon,
    /// [number]@myboostmobile.com
    BoostMobile,
    /// [number]@sms.mycricket.com
    Cricket,
    /// [number]@mymetropcs.com
    MetroPCS,
    /// [number]@mmst5.tracfone.com
    Tracfone,
    /// [number]@email.uscc.net
    USCellular,
    /// [number]@vmobl.com
    VirginMobile,
    /// Other carrier, the string provided is
    /// the domain for this carrier
    Other { domain: String },
}

impl std::str::FromStr for Carrier {
    type Err = Error;
    /// This should always succeed
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "att" => Self::ATT,
            "sprint" => Self::Sprint,
            "tmobile" => Self::TMobile,
            "verizon" => Self::Verizon,
            "boost" => Self::BoostMobile,
            "cricket" => Self::Cricket,
            "metropcs" => Self::MetroPCS,
            "tracfone" => Self::Tracfone,
            "uscellular" => Self::USCellular,
            "virgin" => Self::VirginMobile,
            _ => Self::Other {
                domain: s.to_string(),
            },
        })
    }
}

/// A phone number and
/// mobile carrier pair
/// for sending a text
/// message
#[derive(Debug)]
pub struct Destination {
    pub number: String,
    pub carrier: Carrier,
}

impl Destination {
    /// Creates a new destination with
    /// the provided phone number and
    /// carrier. The phone number provided
    /// will have all not decimal digits
    /// stripped from it (It is not validated in any way).
    pub fn new(number: &str, carrier: &Carrier) -> Self {
        let number = number.chars().filter(|c| c.is_digit(10)).collect();
        Self {
            number,
            carrier: carrier.clone(),
        }
    }

    pub fn address(&self) -> String {
        format!("{}@{}", self.number, self.carrier.get_domain())
    }
}

impl Carrier {
    pub fn get_domain(&self) -> &str {
        match self {
            Carrier::ATT => "txt.att.net",
            Carrier::Sprint => "messaging.sprintpcs.com",
            Carrier::TMobile => "tmomail.net",
            Carrier::Verizon => "vtext.com",
            Carrier::BoostMobile => "myboostmobile.com",
            Carrier::Cricket => "sms.mycricket.com",
            Carrier::MetroPCS => "mymetropcs.com",
            Carrier::Tracfone => "mmst5.tracfone.com",
            Carrier::USCellular => "email.uscc.net",
            Carrier::VirginMobile => "vmobl.com",
            Carrier::Other { domain } => domain,
        }
    }
}