<?php
namespace app\common\library;
use think\Config;
class Email
{
protected static $instance;
protected $mail = [];
protected $_error = '';
public $options = [
'charset' => 'utf-8', 'debug' => 0, ];
public static function instance($options = [])
{
if (is_null(self::$instance))
{
self::$instance = new static($options);
}
return self::$instance;
}
public function __construct($options = [])
{
if ($config = Config::get('site'))
{
$this->options = array_merge($this->options, $config);
}
$this->options = array_merge($this->options, $options);
vendor('phpmailer.phpmailer.PHPMailerAutoload');
$securArr = [1 => 'tls', 2 => 'ssl'];
$this->mail = new \PHPMailer(true);
$this->mail->CharSet = $this->options['charset'];
$this->mail->SMTPDebug = $this->options['debug'];
$this->mail->isSMTP();
$this->mail->SMTPAuth = true;
$this->mail->Host = $this->options['mail_smtp_host'];
$this->mail->Username = $this->options['mail_smtp_user'];
$this->mail->Password = $this->options['mail_smtp_pass'];
$this->mail->SMTPSecure = isset($securArr[$this->options['mail_verify_type']]) ? $securArr[$this->options['mail_verify_type']] : '';
$this->mail->Port = $this->options['mail_smtp_port'];
$this->from($this->options['mail_from']);
}
public function subject($subject)
{
$this->options['subject'] = $subject;
return $this;
}
public function from($email, $name = '')
{
$this->options['from'] = $email;
$this->options['from_name'] = $name;
return $this;
}
public function to($email, $name = '')
{
$this->options['to'] = $email;
$this->options['to_name'] = $name;
return $this;
}
public function message($body, $ishtml = true)
{
$this->options['body'] = $body;
$this->options['ishtml'] = $ishtml;
return $this;
}
public function getError()
{
return $this->_error;
}
protected function setError($error)
{
$this->_error = $error;
}
public function send()
{
$result = false;
switch ($this->options['mail_type'])
{
case 1:
$this->mail->setFrom($this->options['from'], $this->options['from_name']);
$this->mail->addAddress($this->options['to'], $this->options['to_name']);
$this->mail->Subject = $this->options['subject'];
if ($this->options['ishtml'])
{
$this->mail->msgHTML($this->options['body']);
}
else
{
$this->mail->Body = $this->options['body'];
}
try
{
$result = $this->mail->send();
}
catch (\phpmailerException $e)
{
$this->setError($e->getMessage());
}
$this->setError($result ? '' : $this->mail->ErrorInfo);
break;
case 2:
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-type: text/html; charset=" . $this->options['charset'] . "\r\n";
$headers .= "To: {$this->options['to_name']} <{$this->options['to']}>\r\n"; $headers .= "From: {$this->options['from_name']} <{$this->options['from']}>\r\n"; $result = mail($this->options['to'], $this->options['subject'], $this->options['body'], $headers);
$this->setError($result ? '' : error_get_last()['message']);
break;
default:
$this->setError(__('Mail already closed'));
break;
}
return $result;
}
}