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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! # email-format
//!
//! This crate allows you to construct email messages in a way that assures that
//! they are compliant with relevant email standards (especially RFC 5322). Invalid
//! data submitted will return a ParseError.
//!
//! The main structure to work with is `Email`. It has many functions to set or add
//! headers and to set the body. All of these will accept an `&str` or `&[u8]` argument
//! and attempt to parse it. These setters return a `Result<(), ParseError>` as the
//! parse may fail.
//!
//! ## Composition
//!
//! You can compose an email like this:
//!
//! ```
//! use email_format::Email;
//!
//! let mut email = Email::new(
//!     "myself@mydomain.com",  // "From:"
//!     "Wed, 5 Jan 2015 15:13:05 +1300" // "Date:"
//! ).unwrap();
//! email.set_sender("from_myself@mydomain.com").unwrap();
//! email.set_reply_to("My Mailer <no-reply@mydomain.com>").unwrap();
//! email.set_to("You <you@yourdomain.com>").unwrap();
//! email.set_cc("Our Friend <friend@frienddomain.com>").unwrap();
//! email.set_message_id("<id/20161128115731.29084.maelstrom@mydomain.com>").unwrap();
//! email.set_subject("Hello Friend").unwrap();
//! email.set_body("Good to hear from you.\r\n\
//!                 I wish you the best.\r\n\
//!                 \r\n\
//!                 Your Friend").unwrap();
//!
//! println!("{}", email);
//! ```
//!
//! This outputs:
//!
//! ```text
//! Date:Wed, 5 Jan 2015 15:13:05 +1300
//! From:myself@mydomain.com
//! Sender:from_myself@mydomain.com
//! Reply-To:My Mailer <no-reply@mydomain.com>
//! To:You <you@yourdomain.com>
//! Cc:Our Friend <friend@frienddomain.com>
//! Message-ID:<id/20161128115731.29084.maelstrom@mydomain.com>
//! Subject:Hello Friend
//!
//! Good to hear from you.
//! I wish you the best.
//!
//! Your Friend
//! ```
//!
//! ## Parsing
//!
//! The following code will parse the input bytes (or panic if the parse
//! failed), and leave any trailing bytes in the remainder, which should
//! be checked to verify it is empty.
//!
//! ```
//! use email_format::Email;
//! use email_format::rfc5322::Parsable;
//!
//! let input = "Date: Wed, 5 Jan 2015 15:13:05 +1300\r\n\
//!              From: myself@mydomain.com\r\n\
//!              Sender: from_myself@mydomain.com\r\n\
//!              My-Crazy-Field: this is my field\r\n\
//!              Subject: Hello Friend\r\n\
//!              \r\n\
//!              Good to hear from you.\r\n\
//!              I wish you the best.\r\n\
//!              \r\n\
//!              Your Friend".as_bytes();
//!  let (mut email, remainder) = Email::parse(&input).unwrap();
//!  assert_eq!(remainder.len(), 0);
//! ```
//!
//! ## Usage with lettre and/or mailstrom
//!
//! If compiled with the `lettre` feature, you can generate a `SimpleSendableEmail`
//! like this, and then use the `lettre` crate (or `mailstrom`) to send it.
//!
//! ```ignore
//! let simple_sendable_email = email.as_simple_sendable_email().unwrap();
//! ```

extern crate buf_read_ext;

#[cfg(feature="time")]
extern crate time;
#[cfg(feature="chrono")]
extern crate chrono;
#[cfg(feature="lettre")]
extern crate lettre;

#[cfg(test)]
mod tests;

/// This module contains nitty-gritty details about parsing, storage, and streaming
/// an `Email`.
pub mod rfc5322;

use std::io::Write;
use std::io::Error as IoError;
use std::fmt;

use rfc5322::{Message, Fields, Field};
use rfc5322::{Parsable, Streamable};
use rfc5322::error::ParseError;
use rfc5322::Body;
use rfc5322::headers::{From, OrigDate, Sender, ReplyTo, To, Cc, Bcc, MessageId,
                           InReplyTo, References, Subject, Comments, Keywords,
                           OptionalField};

/// Attempt to construct `Self` via a conversion (borrowed from rust `std`)
///
/// This TryFrom trait is defined in the rust std library but is behind a
/// feature gate.  We place it here so that people using stable compilers
/// can still use our crate.  In the future, the std trait should be used.
pub trait TryFrom<T>: Sized {
    /// The type returned in the event of a conversion error.
    type Error;

    /// Performs the conversion.
    fn try_from(T) -> Result<Self, Self::Error>;
}

// We implement TryFrom from T to T with our ParseError for crate ergonomics
// (Rust won't let it be implemented with an unconstrained error type)
impl<T> TryFrom<T> for T {
    type Error = ::rfc5322::error::ParseError;
    fn try_from(input: T) -> Result<T, Self::Error> {
        Ok(input)
    }
}

#[derive(Debug, Clone)]
pub struct Email {
    message: Message,
}

impl Email {
    /// Create a new email structure.  The `From` address and `Date` fields are
    /// required in all valid emails, thus you must pass these in.
    pub fn new<F,D>(from: F, date: D) -> Result<Email, ParseError>
        where From: TryFrom<F, Error=ParseError>, OrigDate: TryFrom<D, Error=ParseError>
    {
        Ok(Email {
            message: Message {
                fields: Fields {
                    trace_blocks: vec![],
                    fields: vec![
                        Field::OrigDate(try!(TryFrom::try_from(date))),
                        Field::From(try!(TryFrom::try_from(from))) ],
                },
                body: None,
            }
        })
    }

    /// Replace the `Date` field in the email
    pub fn set_date<D>(&mut self, date: D) -> Result<(), ParseError>
        where OrigDate: TryFrom<D, Error=ParseError>
    {
        let value: OrigDate = try!(TryFrom::try_from(date));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::OrigDate(_) = *field {
                *field = Field::OrigDate(value);
                return Ok(())
            }
        }
        unreachable!()
    }
    /// Fetch the `Date` field from the email
    pub fn get_date(&self) -> OrigDate {
        for field in self.message.fields.fields.iter() {
            if let Field::OrigDate(ref d) = *field {
                return d.clone();
            }
        }
        unreachable!()
    }

    /// Replace the `From` field in the email
    pub fn set_from<F>(&mut self, from: F) -> Result<(), ParseError>
        where From: TryFrom<F, Error=ParseError>
    {
        let value: From = try!(TryFrom::try_from(from));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::From(_) = *field {
                *field = Field::From(value);
                return Ok(());
            }
        }
        unreachable!()
    }
    /// Fetch the `From` field from the email
    pub fn get_from(&self) -> From {
        for field in self.message.fields.fields.iter() {
            if let Field::From(ref f) = *field {
                return f.clone()
            }
        }
        unreachable!()
    }

    /// Set or replace the `Sender` field in the email
    pub fn set_sender<S>(&mut self, sender: S) -> Result<(), ParseError>
        where Sender: TryFrom<S, Error=ParseError>
    {
        let value: Sender = try!(TryFrom::try_from(sender));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::Sender(_) = *field {
                *field = Field::Sender(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::Sender(value));
        Ok(())
    }
    /// Fetch the `Sender` field from the email
    pub fn get_sender(&self) -> Option<Sender> {
        for field in self.message.fields.fields.iter() {
            if let Field::Sender(ref s) = *field {
                return Some(s.clone());
            }
        }
        None
    }
    /// Remove the `Sender` field from the email
    pub fn clear_sender(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::Sender(_) = *field { false } else { true }
        });
    }

    /// Set or replace the `Reply-To` field in the email
    pub fn set_reply_to<R>(&mut self, reply_to: R) -> Result<(), ParseError>
        where ReplyTo: TryFrom<R, Error=ParseError>
    {
        let value: ReplyTo = try!(TryFrom::try_from(reply_to));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::ReplyTo(_) = *field {
                *field = Field::ReplyTo(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::ReplyTo(value));
        Ok(())
    }
    /// Fetch the `Reply-To` field from the email
    pub fn get_reply_to(&self) -> Option<ReplyTo> {
        for field in self.message.fields.fields.iter() {
            if let Field::ReplyTo(ref rt) = *field {
                return Some(rt.clone())
            }
        }
        None
    }
    /// Remove the `Reply-To` field from the email
    pub fn clear_reply_to(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::ReplyTo(_) = *field { false } else { true }
        });
    }

    /// Set or replace the `To` field in the email
    pub fn set_to<T>(&mut self, to: T) -> Result<(), ParseError>
        where To: TryFrom<T, Error=ParseError>
    {
        let value: To = try!(TryFrom::try_from(to));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::To(_) = *field {
                *field = Field::To(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::To(value));
        Ok(())
    }
    /// Fetch the `To` field from the email
    pub fn get_to(&self) -> Option<To> {
        for field in self.message.fields.fields.iter() {
            if let Field::To(ref t) = *field {
                return Some(t.clone())
            }
        }
        None
    }
    /// Remove the `To` field from the email
    pub fn clear_to(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::To(_) = *field { false } else { true }
        });
    }

    /// Set or replace the `Cc` field in the email
    pub fn set_cc<C>(&mut self, cc: C) -> Result<(), ParseError>
        where Cc: TryFrom<C, Error=ParseError>
    {
        let value: Cc = try!(TryFrom::try_from(cc));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::Cc(_) = *field {
                *field = Field::Cc(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::Cc(value));
        Ok(())
    }
    /// Fetch the `Cc` field from the email
    pub fn get_cc(&self) -> Option<Cc> {
        for field in self.message.fields.fields.iter() {
            if let Field::Cc(ref cc) = *field {
                return Some(cc.clone())
            }
        }
        None
    }
    /// Remove the `Cc` field from the email
    pub fn clear_cc(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::Cc(_) = *field { false } else { true }
        });
    }

    /// Set or replace the `Bcc` field in the email
    pub fn set_bcc<B>(&mut self, bcc: B) -> Result<(), ParseError>
        where Bcc: TryFrom<B, Error=ParseError>
    {
        let value: Bcc = try!(TryFrom::try_from(bcc));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::Bcc(_) = *field {
                *field = Field::Bcc(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::Bcc(value));
        Ok(())
    }
    /// Fetch the `Bcc` field from the email
    pub fn get_bcc(&self) -> Option<Bcc> {
        for field in self.message.fields.fields.iter() {
            if let Field::Bcc(ref b) = *field {
                return Some(b.clone())
            }
        }
        None
    }
    /// Remove the `Bcc` field from the email
    pub fn clear_bcc(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::Bcc(_) = *field { false } else { true }
        });
    }

    /// Set or replace the `Message-ID` field in the email
    pub fn set_message_id<M>(&mut self, message_id: M) -> Result<(), ParseError>
        where MessageId: TryFrom<M, Error=ParseError>
    {
        let value: MessageId = try!(TryFrom::try_from(message_id));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::MessageId(_) = *field {
                *field = Field::MessageId(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::MessageId(value));
        Ok(())
    }
    /// Fetch the `Message-ID` field from the email
    pub fn get_message_id(&self) -> Option<MessageId> {
        for field in self.message.fields.fields.iter() {
            if let Field::MessageId(ref m) = *field {
                return Some(m.clone())
            }
        }
        None
    }
    /// Remove the `Message-ID` field from the email
    pub fn clear_message_id(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::MessageId(_) = *field { false } else { true }
        });
    }

    /// Set or replace the `In-Reply-To` field in the email
    pub fn set_in_reply_to<I>(&mut self, in_reply_to: I) -> Result<(), ParseError>
        where InReplyTo: TryFrom<I, Error=ParseError>
    {
        let value: InReplyTo = try!(TryFrom::try_from(in_reply_to));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::InReplyTo(_) = *field {
                *field = Field::InReplyTo(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::InReplyTo(value));
        Ok(())
    }
    /// Fetch the `In-Reply-To` field from the email
    pub fn get_in_reply_to(&self) -> Option<InReplyTo> {
        for field in self.message.fields.fields.iter() {
            if let Field::InReplyTo(ref x) = *field {
                return Some(x.clone())
            }
        }
        None
    }
    /// Remove the `In-Reply-To` field from the email
    pub fn clear_in_reply_to(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::InReplyTo(_) = *field { false } else { true }
        });
    }

    /// Set or replace the `References` field in the email
    pub fn set_references<R>(&mut self, references: R) -> Result<(), ParseError>
        where References: TryFrom<R, Error=ParseError>
    {
        let value: References = try!(TryFrom::try_from(references));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::References(_) = *field {
                *field = Field::References(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::References(value));
        Ok(())
    }
    /// Fetch the `References` field from the email
    pub fn get_references(&self) -> Option<References> {
        for field in self.message.fields.fields.iter() {
            if let Field::References(ref x) = *field {
                return Some(x.clone())
            }
        }
        None
    }
    /// Remove the `References` field from the email
    pub fn clear_references(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::References(_) = *field { false } else { true }
        });
    }

    /// Set or replace the `Subject` field in the email
    pub fn set_subject<S>(&mut self, subject: S) -> Result<(), ParseError>
        where Subject: TryFrom<S, Error=ParseError>
    {
        let value: Subject = try!(TryFrom::try_from(subject));
        for field in self.message.fields.fields.iter_mut() {
            if let Field::Subject(_) = *field {
                *field = Field::Subject(value);
                return Ok(());
            }
        }
        self.message.fields.fields.push(Field::Subject(value));
        Ok(())
    }
    /// Fetch the `Subject` field from the email
    pub fn get_subject(&self) -> Option<Subject> {
        for field in self.message.fields.fields.iter() {
            if let Field::Subject(ref x) = *field {
                return Some(x.clone())
            }
        }
        None
    }
    /// Remove the `Subject` field from the email
    pub fn clear_subject(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::Subject(_) = *field { false } else { true }
        });
    }

    /// Add a `Comments` field in the email. This may be in addition to
    /// existing `Comments` fields.
    pub fn add_comments<C>(&mut self, comments: C) -> Result<(), ParseError>
        where Comments: TryFrom<C, Error=ParseError>
    {
        let value: Comments = try!(TryFrom::try_from(comments));
        self.message.fields.fields.push(Field::Comments(value));
        Ok(())
    }
    /// Fetch all `Comments` fields from the email
    pub fn get_comments(&self) -> Vec<Comments> {
        let mut output: Vec<Comments> = Vec::new();
        for field in self.message.fields.fields.iter() {
            if let Field::Comments(ref x) = *field {
                output.push(x.clone());
            }
        }
        output
    }
    /// Remove all `Comments` fields from the email
    pub fn clear_comments(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::Comments(_) = *field { false } else { true }
        });
    }

    /// Add a `Keywords` field in the email. This may be in addition to existing
    /// `Keywords` fields.
    pub fn add_keywords<K>(&mut self, keywords: K) -> Result<(), ParseError>
        where Keywords: TryFrom<K, Error=ParseError>
    {
        let value: Keywords = try!(TryFrom::try_from(keywords));
        self.message.fields.fields.push(Field::Keywords(value));
        Ok(())
    }
    /// Fetch all `Keywords` fields from the email
    pub fn get_keywords(&self) -> Vec<Keywords> {
        let mut output: Vec<Keywords> = Vec::new();
        for field in self.message.fields.fields.iter() {
            if let Field::Keywords(ref x) = *field {
                output.push(x.clone());
            }
        }
        output
    }
    /// Remove all `Keywords` fields from the email
    pub fn clear_keywords(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::Keywords(_) = *field { false } else { true }
        });
    }

    /// Add an optional field to the email. This may be in addition to existing
    /// optional fields.
    pub fn add_optional_field<O>(&mut self, optional_field: O) -> Result<(), ParseError>
        where OptionalField: TryFrom<O, Error=ParseError>
    {
        let value: OptionalField = try!(TryFrom::try_from(optional_field));
        self.message.fields.fields.push(Field::OptionalField(value));
        Ok(())
    }
    /// Fetch all optional fields from the email
    pub fn get_optional_fields(&self) -> Vec<OptionalField> {
        let mut output: Vec<OptionalField> = Vec::new();
        for field in self.message.fields.fields.iter() {
            if let Field::OptionalField(ref x) = *field {
                output.push(x.clone());
            }
        }
        output
    }
    /// Clear all optional fields from the email
    pub fn clear_optional_fields(&mut self) {
        self.message.fields.fields.retain(|field| {
            if let Field::OptionalField(_) = *field {
                false
            } else {
                true
            }
        })
    }

    // TBD: trace
    // TBD: resent-date
    // TBD: resent-from
    // TBD: resent-sender
    // TBD: resent-to
    // TBD: resent-cc
    // TBD: resent-bcc
    // TBD: resent-msg-id

    /// Set or replace the `Body` in the email
    pub fn set_body<B>(&mut self, body: B) -> Result<(), ParseError>
        where Body: TryFrom<B, Error=ParseError>
    {
        let value: Body = try!(TryFrom::try_from(body));
        self.message.body = Some(value);
        Ok(())
    }
    /// Fetch the `Body` from the email
    pub fn get_body(&self) -> Option<Body> {
        self.message.body.clone()
    }
    /// Remove the `Body` from the email, leaving an empty body
    pub fn clear_body(&mut self) {
        self.message.body = None;
    }

    /// Stream the email into a byte vector and return that
    pub fn as_bytes(&self) -> Vec<u8> {
        let mut output: Vec<u8> = Vec::new();
        let _ = self.stream(&mut output); // no IoError ought to occur.
        output
    }

    /// Stream the email into a byte vector, convert to a String, and
    /// return that
    pub fn as_string(&self) -> String {
        let mut vec: Vec<u8> = Vec::new();
        let _ = self.stream(&mut vec); // no IoError ought to occur.
        unsafe {
            // rfc5322 formatted emails fall within utf8, so this should not be
            // able to fail
            String::from_utf8_unchecked(vec)
        }
    }

    /// Create a `lettre::SimpleSendableEmail` from this Email.
    ///
    /// We require `&mut self` because we temporarily strip off the Bcc line
    /// when we generate the message, and then we put it back afterwards to
    /// leave `self` in a functionally unmodified state.
    #[cfg(feature="lettre")]
    pub fn as_simple_sendable_email(&mut self) ->
        Result<::lettre::SimpleSendableEmail, &'static str>
    {
        use lettre::{SimpleSendableEmail, EmailAddress};
        use rfc5322::types::Address;

        let mut recipients: Vec<Address> = Vec::new();
        if let Some(to) = self.get_to() {
            recipients.extend((to.0).0);
        }
        if let Some(cc) = self.get_cc() {
            recipients.extend((cc.0).0);
        }
        if let Some(bcc) = self.get_bcc() {
            if let Bcc::AddressList(al) = bcc {
                recipients.extend(al.0);
            }
        }

        // Remove duplicates
        recipients.dedup();

        // Map to lettre::EmailAddress
        let recipients: Vec<EmailAddress> = recipients
            .iter()
            .map(|address| EmailAddress::new(format!("{}", address)))
            .collect();

        let from_addr = EmailAddress::new(format!("{}", self.get_from()));

        let message_id = match self.get_message_id() {
            Some(mid) => format!("{}@{}", mid.0.id_left, mid.0.id_right),
            None => return Err("email has no Message-ID"),
        };

        // Remove Bcc header before creating body (RFC 5321 section 7.2)
        let maybe_bcc = self.get_bcc();
        self.clear_bcc();

        let message = format!("{}", self);

        // Put the Bcc back to restore the caller's argument
        if let Some(bcc) = maybe_bcc {
            if let Err(_) = self.set_bcc(bcc) {
                return Err("Unable to restore the Bcc line");
            }
        }

        Ok(SimpleSendableEmail::new(from_addr, recipients, message_id, message))
    }
}

impl Parsable for Email {
    fn parse(input: &[u8]) -> Result<(Self, &[u8]), ParseError> {
        let mut rem = input;
        match Message::parse(rem).map(|(value, r)| { rem = r; value }) {
            Ok(message) => Ok((Email { message: message}, rem)),
            Err(e) => Err(ParseError::Parse("Email", Box::new(e)))
        }
    }
}

impl Streamable for Email {
    fn stream<W: Write>(&self, w: &mut W) -> Result<usize, IoError> {
        self.message.stream(w)
    }
}

impl fmt::Display for Email {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let bytes = self.as_bytes();
        unsafe {
            // rfc5322 formatted emails fall within utf8, so this should not be
            // able to fail
            write!(f, "{}", ::std::str::from_utf8_unchecked(&*bytes))
        }
    }
}