db = new Pdo; $this->config = Config::get(); $this->table = new Table(); $this->tbl_mailTemplate = $this->table->email_template; $this->conf = new \stdClass(); $this->loadconf(); $this->smtp(); if(empty($mail)) { $this->mail = new Message(); }else{ $this->mail = $mail; } $this->mail->setEncoding("UTF-8"); } private function loadconf() { $email_cfg = Config::get('email'); $this->email_cfg = $email_cfg->config; } private function smtp() { $this->transport = new SmtpTransport(); $options = new SmtpOptions(array( 'name' => $this->email_cfg->hostname, 'host' => $this->email_cfg->host, 'port' => $this->email_cfg->port, // Notice port change for TLS is 587 'connection_class' => $this->email_cfg->auth, 'connection_config' => array( 'username' => $this->email_cfg->username, 'password' => $this->email_cfg->password, 'ssl' => $this->email_cfg->ssl, ), )); $this->transport->setOptions($options); } //设置默认发件人 public function setDefaultForm() { $this->mail->setFrom($this->email_cfg->username,$this->email_cfg->name); } //加载模板 public function loadTemplate($id,$data){ if(is_numeric($id)) { $sql = "SELECT * FROM {$this->tbl_mailTemplate} WHERE id='".$id."'"; }else{ $sql = "SELECT * FROM {$this->tbl_mailTemplate} WHERE \"template\"='".$id."'"; } $rs = $this->db->query($sql); $row = $rs->fetch(); $subject = $row['subject']; $body = $row['body']; if(count($data) > 0) { $patterns = array(); $replacements = array(); foreach($data as $k=>$v) { $patterns[]='/{'.$k.'}/i'; $replacements[]=$v; } ksort($patterns); ksort($replacements); $body = preg_replace($patterns, $replacements, $body); $subject = preg_replace($patterns, $replacements, $subject); }//count($this->data) $this->subject = $subject; $this->body = $body; if(isset($row['type'])) $this->type = $row['type']; }//加载模板 public function addTo($email,$name) { $this->mail->addTo($email,$name); } //使用loadTemplate 的结果发送邮件 //在此之前需要使用 $this->mail->addTo()添加收件人 public function send($from = NULL){ if(empty($this->subject) || empty($this->body)) { return "邮件信息不完整"; } if($this->type == 'html') { $bodyPart = new \Zend\Mime\Message(); $bodyMessage = new \Zend\Mime\Part($this->body); $bodyMessage->type = 'text/html'; $bodyPart->setParts(array($bodyMessage)); $this->mail->setBody($bodyPart); }else{ $this->mail->setBody($this->body); } if(empty($from)) { $this->setDefaultForm(); }else{ $this->mail->setFrom($from['email'],$from['name']); } $this->mail->setSubject($this->subject); $this->transport->send($this->mail); } }