Email.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: chendeben
  5. * Date: 2018/8/10
  6. * Time: 上午11:22
  7. */
  8. namespace Heanup\Library;
  9. use Heanup\App\Api\Config\GlobalConfig;
  10. use Heanup\Frame\Logger;
  11. use PHPMailer\PHPMailer\Exception;
  12. use PHPMailer\PHPMailer\PHPMailer;
  13. class Email
  14. {
  15. private static $instance;
  16. private $mail;
  17. public function __construct()
  18. {
  19. $config = GlobalConfig::getData();
  20. $this->mail = new PHPMailer();
  21. $this->mail->CharSet = 'UTF-8';
  22. $this->mail->isSMTP(); // Set mailer to use SMTP
  23. $this->mail->Host = $config['host']; // Specify main and backup SMTP servers
  24. $this->mail->SMTPAuth = $config['auth']; // Enable SMTP authentication
  25. $this->mail->Username = $config['user']; // SMTP username
  26. $this->mail->Password = $config['pwd']; // SMTP password
  27. $this->mail->SMTPSecure = $config['secure']; // Enable TLS encryption, `ssl` also accepted
  28. $this->mail->Port = $config['port']; // TCP port to connect to
  29. try {
  30. $this->mail->setFrom($config['user'], $config['from']);
  31. } catch (Exception $e) {
  32. }
  33. $this->mail->addCustomHeader('X-Priority', '1\r\n');
  34. }
  35. public static function instance()
  36. {
  37. if (!self::$instance) {
  38. self::$instance = new self();
  39. }
  40. return self::$instance;
  41. }
  42. /**
  43. * @param array $receipt 收件人地址
  44. * @param string $subject 邮件标题
  45. * @param string $body 邮件内容
  46. * @param array $attachment 附件
  47. * @param bool $is_html 是否HTML格式
  48. * @return bool
  49. * @throws Exception
  50. */
  51. public function sendMail(array $receipt, string $subject, string $body, array $attachment = array(), bool $is_html = true)
  52. {
  53. foreach ($receipt as $list) {
  54. $this->mail->addAddress($list);
  55. }
  56. try {
  57. if ($attachment) {
  58. $this->mail->addAttachment($attachment['path'], $attachment['name']);
  59. }
  60. } catch (Exception $e) {
  61. }
  62. $this->mail->isHTML($is_html);
  63. $this->mail->Subject = $subject;
  64. $this->mail->Body = $body;
  65. try {
  66. if (!$this->mail->send()) {
  67. Logger::error($this->mail->ErrorInfo, 'mail_err');
  68. return false;
  69. }
  70. } catch (Exception $e) {
  71. Logger::error($this->mail->ErrorInfo, 'mail_err');
  72. }
  73. return true;
  74. }
  75. }