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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
//! Simple email (very incomplete)

use std::fmt;
use std::fmt::{Display, Formatter};

use email_format::{Header, Mailbox, MimeMessage};
use time::{Tm, now};
use uuid::Uuid;

/// Converts an adress or an address with an alias to a `Address`
pub trait ToHeader {
    /// Converts to a `Header` struct
    fn to_header(&self) -> Header;
}

impl ToHeader for Header {
    fn to_header(&self) -> Header {
        (*self).clone()
    }
}

impl<'a> ToHeader for (&'a str, &'a str) {
    fn to_header(&self) -> Header {
        let (name, value) = *self;
        Header::new(name.to_string(), value.to_string())
    }
}

/// Converts an adress or an address with an alias to a `Mailbox`
pub trait ToMailbox {
    /// Converts to a `Mailbox` struct
    fn to_mailbox(&self) -> Mailbox;
}

impl ToMailbox for Mailbox {
    fn to_mailbox(&self) -> Mailbox {
        (*self).clone()
    }
}

impl<'a> ToMailbox for &'a str {
    fn to_mailbox(&self) -> Mailbox {
        Mailbox::new(self.to_string())
    }
}

impl<'a> ToMailbox for (&'a str, &'a str) {
    fn to_mailbox(&self) -> Mailbox {
        let (address, alias) = *self;
        Mailbox::new_with_name(alias.to_string(), address.to_string())
    }
}

/// Builds an `Email` structure
#[derive(PartialEq,Eq,Clone,Debug)]
pub struct EmailBuilder {
    /// Message
    message: MimeMessage,
    /// The enveloppe recipients addresses
    to: Vec<String>,
    /// The enveloppe sender address
    from: Option<String>,
    /// Date issued
    date_issued: bool,
}

/// Simple email representation
#[derive(PartialEq,Eq,Clone,Debug)]
pub struct Email {
    /// Message
    message: MimeMessage,
    /// The enveloppe recipients addresses
    to: Vec<String>,
    /// The enveloppe sender address
    from: String,
    /// Message-ID
    message_id: Uuid,
}

impl Display for Email {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}", self.message.as_string())
    }
}

impl EmailBuilder {
    /// Creates a new empty email
    pub fn new() -> EmailBuilder {
        EmailBuilder {
            message: MimeMessage::new_blank_message(),
            to: vec![],
            from: None,
            date_issued: false,
        }
    }

    /// Sets the email body
    pub fn body(mut self, body: &str) -> EmailBuilder {
        self.message.body = body.to_string();
        self
    }

    /// Add a generic header
    pub fn add_header<A: ToHeader>(mut self, header: A) -> EmailBuilder {
        self.insert_header(header);
        self
    }

    fn insert_header<A: ToHeader>(&mut self, header: A) {
        self.message.headers.insert(header.to_header());
    }

    /// Adds a `From` header and store the sender address
    pub fn from<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
        let mailbox = address.to_mailbox();
        self.insert_header(("From", mailbox.to_string().as_ref()));
        self.from = Some(mailbox.address);
        self
    }

    /// Adds a `To` header and store the recipient address
    pub fn to<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
        let mailbox = address.to_mailbox();
        self.insert_header(("To", mailbox.to_string().as_ref()));
        self.to.push(mailbox.address);
        self
    }

    /// Adds a `Cc` header and store the recipient address
    pub fn cc<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
        let mailbox = address.to_mailbox();
        self.insert_header(("Cc", mailbox.to_string().as_ref()));
        self.to.push(mailbox.address);
        self
    }

    /// Adds a `Reply-To` header
    pub fn reply_to<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
        let mailbox = address.to_mailbox();
        self.insert_header(("Reply-To", mailbox.to_string().as_ref()));
        self
    }

    /// Adds a `Sender` header
    pub fn sender<A: ToMailbox>(mut self, address: A) -> EmailBuilder {
        let mailbox = address.to_mailbox();
        self.insert_header(("Sender", mailbox.to_string().as_ref()));
        self.from = Some(mailbox.address);
        self
    }

    /// Adds a `Subject` header
    pub fn subject(mut self, subject: &str) -> EmailBuilder {
        self.insert_header(("Subject", subject));
        self
    }

    /// Adds a `Date` header with the given date
    pub fn date(mut self, date: &Tm) -> EmailBuilder {
        self.insert_header(("Date", Tm::rfc822z(date).to_string().as_ref()));
        self.date_issued = true;
        self
    }

    /// Build the Email
    pub fn build(mut self) -> Result<Email, &'static str> {
        if self.from.is_none() {
            return Err("No from address");
        }
        if self.to.is_empty() {
            return Err("No to address");
        }

        if !self.date_issued {
            self.insert_header(("Date", Tm::rfc822z(&now()).to_string().as_ref()));
        }

        let message_id = Uuid::new_v4();

        match Header::new_with_value("Message-ID".to_string(),
                                     format!("<{}.lettre@localhost>", message_id)) {
            Ok(header) => self.insert_header(header),
            Err(_) => (),
        }

        self.message.update_headers();

        Ok(Email {
            message: self.message,
            to: self.to,
            from: self.from.unwrap(),
            message_id: message_id,
        })
    }
}


/// Email sendable by an SMTP client
pub trait SendableEmail {
    /// From address
    fn from_address(&self) -> String;
    /// To addresses
    fn to_addresses(&self) -> Vec<String>;
    /// Message content
    fn message(&self) -> String;
    /// Message ID
    fn message_id(&self) -> String;
}

/// Minimal email structure
pub struct SimpleSendableEmail {
    /// From address
    from: String,
    /// To addresses
    to: Vec<String>,
    /// Message
    message: String,
}

impl SimpleSendableEmail {
    /// Returns a new email
    pub fn new(from_address: &str, to_address: Vec<String>, message: &str) -> SimpleSendableEmail {
        SimpleSendableEmail {
            from: from_address.to_string(),
            to: to_address,
            message: message.to_string(),
        }
    }
}

impl SendableEmail for SimpleSendableEmail {
    fn from_address(&self) -> String {
        self.from.clone()
    }

    fn to_addresses(&self) -> Vec<String> {
        self.to.clone()
    }

    fn message(&self) -> String {
        self.message.clone()
    }

    fn message_id(&self) -> String {
        format!("{}", Uuid::new_v4())
    }
}

impl SendableEmail for Email {
    fn to_addresses(&self) -> Vec<String> {
        self.to.clone()
    }

    fn from_address(&self) -> String {
        self.from.clone()
    }

    fn message(&self) -> String {
        format!("{}", self)
    }

    fn message_id(&self) -> String {
        format!("{}", self.message_id)
    }
}

#[cfg(test)]
mod test {
    use time::now;

    use uuid::Uuid;
    use email_format::{Header, MimeMessage};

    use super::{Email, EmailBuilder, SendableEmail};

    #[test]
    fn test_email_display() {
        let current_message = Uuid::new_v4();

        let mut email = Email {
            message: MimeMessage::new_blank_message(),
            to: vec![],
            from: "".to_string(),
            message_id: current_message,
        };

        email.message.headers.insert(Header::new_with_value("Message-ID".to_string(),
                                                            format!("<{}@rust-smtp>",
                                                                    current_message))
                                         .unwrap());

        email.message
             .headers
             .insert(Header::new_with_value("To".to_string(), "to@example.com".to_string())
                         .unwrap());

        email.message.body = "body".to_string();

        assert_eq!(format!("{}", email),
                   format!("Message-ID: <{}@rust-smtp>\r\nTo: to@example.com\r\n\r\nbody\r\n",
                           current_message));
        assert_eq!(current_message.to_string(), email.message_id());
    }

    #[test]
    fn test_email_builder() {
        let email_builder = EmailBuilder::new();
        let date_now = now();

        let email = email_builder.to("user@localhost")
                                 .from("user@localhost")
                                 .cc(("cc@localhost", "Alias"))
                                 .reply_to("reply@localhost")
                                 .sender("sender@localhost")
                                 .body("Hello World!")
                                 .date(&date_now)
                                 .subject("Hello")
                                 .add_header(("X-test", "value"))
                                 .build()
                                 .unwrap();

        assert_eq!(format!("{}", email),
                   format!("To: <user@localhost>\r\nFrom: <user@localhost>\r\nCc: \"Alias\" \
                            <cc@localhost>\r\nReply-To: <reply@localhost>\r\nSender: \
                            <sender@localhost>\r\nDate: {}\r\nSubject: Hello\r\nX-test: \
                            value\r\nMessage-ID: <{}.lettre@localhost>\r\n\r\nHello World!\r\n",
                           date_now.rfc822z(),
                           email.message_id()));
    }

    #[test]
    fn test_email_sendable() {
        let email_builder = EmailBuilder::new();
        let date_now = now();

        let email = email_builder.to("user@localhost")
                                 .from("user@localhost")
                                 .cc(("cc@localhost", "Alias"))
                                 .reply_to("reply@localhost")
                                 .sender("sender@localhost")
                                 .body("Hello World!")
                                 .date(&date_now)
                                 .subject("Hello")
                                 .add_header(("X-test", "value"))
                                 .build()
                                 .unwrap();

        assert_eq!(email.from_address(), "sender@localhost".to_string());
        assert_eq!(email.to_addresses(),
                   vec!["user@localhost".to_string(), "cc@localhost".to_string()]);
        assert_eq!(email.message(), format!("{}", email));
    }

}