df-helper 0.2.26

df helper tools db cache
Documentation
use json::JsonValue;
use lettre::{Message, SmtpTransport, Transport};
use lettre::transport::smtp::authentication::Credentials;

pub struct Email {
    send_email: String,
    send_pass: String,
    smtp_host: String,
    from: String,
    to_name: String,
    to_mail: String,
    reply_to_name: String,
    reply_to_mail: String,
}

impl Email {
    /// 初始化
    ///
    /// * config 配置文件
    /// ````json
    /// {
    ///   "pop3_host": "pop.test.com",
    ///   "pop3_port": 995,
    ///   "smtp_host": "smtp.test.com",
    ///   "smtp_port": 465,
    ///   "send_email": "tests@email.com",
    ///   "send_pass": ""
    /// }
    /// ````
    pub fn connect(config: JsonValue) -> Self {
        let smtp_host = config["smtp_host"].to_string();
        let send_email = config["send_email"].to_string();
        let send_pass = config["send_pass"].to_string();
        Self {
            send_email: send_email.clone(),
            send_pass,
            smtp_host,
            from: send_email.clone(),
            to_name: String::new(),
            to_mail: String::new(),
            reply_to_name: String::new(),
            reply_to_mail: String::new(),
        }
    }

    /// 发件人
    pub fn from(&mut self, send_email: &str) -> &mut Self {
        self.from = send_email.to_string();
        self
    }
    /// 收件人
    pub fn to(&mut self, name: &str, mail: &str) -> &mut Self {
        self.to_name = name.to_string();
        self.to_mail = mail.to_string();
        self
    }
    /// 抄送人
    pub fn reply_to(&mut self, name: &str, mail: &str) -> &mut Self {
        self.reply_to_name = name.to_string();
        self.reply_to_mail = mail.to_string();
        self
    }
    /// 发送
    pub fn send(&mut self, subject: &str, body: &str) -> bool {
        let email = Message::builder()
            .subject(subject)
            .from(self.from.parse().unwrap())
            .to(format!("{} <{}>", self.to_name, self.to_mail).parse().unwrap());

        let email = {
            if !self.reply_to_name.is_empty() {
                email.reply_to(format!("{} <{}>", self.reply_to_name, self.reply_to_mail).parse().unwrap()).body(body.to_string()).unwrap()
            } else {
                email.body(body.to_string()).unwrap()
            }
        };

        let creds = Credentials::new(self.send_email.to_string(), self.send_pass.to_string());
        let mailer = SmtpTransport::relay(self.smtp_host.as_str())
            .unwrap()
            .credentials(creds)
            .build();
        match mailer.send(&email) {
            Ok(_) => {
                true
            }
            Err(e) => {
                println!("Could not send email: {:?}", e);
                false
            }
        }
    }
}