use std::fmt::{Show, Formatter, Result};
use time::{now, Tm};
use email::header::{ToHeader, Header};
use email::address::ToAddress;
use common::CRLF;
pub mod header;
pub mod address;
pub struct Email {
headers: Vec<Header>,
body: String,
to: Vec<String>,
from: Option<String>,
}
impl Show for Email {
fn fmt(&self, f: &mut Formatter) -> Result {
let mut formatted_headers = String::new();
for header in self.headers.iter() {
formatted_headers.push_str(header.to_string().as_slice());
formatted_headers.push_str(CRLF);
}
f.write(format!("{}{}{}", formatted_headers, CRLF, self.body).as_bytes())
}
}
impl Email {
pub fn new() -> Email {
Email{headers: vec!(), body: "".to_string(), to: vec!(), from: None}
}
pub fn clear(&mut self) {
self.headers.clear();
self.body = "".to_string();
self.to.clear();
self.from = None;
}
pub fn get_to<'a>(&'a self) -> Vec<String> {
if self.to.is_empty() {
panic!("The To field is empty")
}
self.to.clone()
}
pub fn get_from(&self) -> String {
match self.from {
Some(ref from_address) => from_address.clone(),
None => panic!("The From field is empty"),
}
}
pub fn body(&mut self, body: &str) {
self.body = body.to_string();
}
pub fn add_header<A: ToHeader>(&mut self, header: A) {
self.headers.push(header.to_header());
}
pub fn from<A: ToAddress>(&mut self, address: A) {
self.from = Some(address.to_address().get_address());
self.headers.push(
Header::new("From", address.to_address().to_string().as_slice())
);
}
pub fn to<A: ToAddress>(&mut self, address: A) {
self.to.push(address.to_address().get_address());
self.headers.push(
Header::new("To", address.to_address().to_string().as_slice())
);
}
pub fn cc<A: ToAddress>(&mut self, address: A) {
self.to.push(address.to_address().get_address());
self.headers.push(
Header::new("Cc", address.to_address().to_string().as_slice())
);
}
pub fn reply_to<A: ToAddress>(&mut self, address: A) {
self.headers.push(
Header::new("Return-Path", address.to_address().to_string().as_slice())
);
}
pub fn subject(&mut self, subject: &str) {
self.headers.push(
Header::new("Subject", subject)
);
}
pub fn date(&mut self) {
self.headers.push(
Header::new("Date", Tm::rfc822(&now()).to_string().as_slice())
);
}
}