Email.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace app\common\library;
  3. use Throwable;
  4. use think\facade\Lang;
  5. use PHPMailer\PHPMailer\PHPMailer;
  6. /**
  7. * 邮件类
  8. * 继承PHPMailer并初始化好了站点系统配置中的邮件配置信息
  9. */
  10. class Email extends PHPMailer
  11. {
  12. /**
  13. * 是否已在管理后台配置好邮件服务
  14. * @var bool
  15. */
  16. public bool $configured = false;
  17. /**
  18. * 默认配置
  19. * @var array
  20. */
  21. public array $options = [
  22. 'charset' => 'utf-8', //编码格式
  23. 'debug' => true, //调式模式
  24. 'lang' => 'zh_cn',
  25. ];
  26. /**
  27. * 构造函数
  28. * @param array $options
  29. * @throws Throwable
  30. */
  31. public function __construct(array $options = [])
  32. {
  33. $this->options = array_merge($this->options, $options);
  34. parent::__construct($this->options['debug']);
  35. $langSet = Lang::getLangSet();
  36. if ($langSet == 'zh-cn' || !$langSet) $langSet = 'zh_cn';
  37. $this->options['lang'] = $this->options['lang'] ?: $langSet;
  38. $this->setLanguage($this->options['lang'], root_path() . 'vendor' . DIRECTORY_SEPARATOR . 'phpmailer' . DIRECTORY_SEPARATOR . 'phpmailer' . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR);
  39. $this->CharSet = $this->options['charset'];
  40. $sysMailConfig = get_sys_config('', 'mail');
  41. $this->configured = true;
  42. foreach ($sysMailConfig as $item) {
  43. if (!$item) {
  44. $this->configured = false;
  45. }
  46. }
  47. if ($this->configured) {
  48. $this->Host = $sysMailConfig['smtp_server'];
  49. $this->SMTPAuth = true;
  50. $this->Username = $sysMailConfig['smtp_user'];
  51. $this->Password = $sysMailConfig['smtp_pass'];
  52. $this->SMTPSecure = $sysMailConfig['smtp_verification'] == 'SSL' ? self::ENCRYPTION_SMTPS : self::ENCRYPTION_STARTTLS;
  53. $this->Port = $sysMailConfig['smtp_port'];
  54. $this->setFrom($sysMailConfig['smtp_sender_mail'], $sysMailConfig['smtp_user']);
  55. }
  56. }
  57. public function setSubject($subject)
  58. {
  59. $this->Subject = "=?utf-8?B?" . base64_encode($subject) . "?=";
  60. }
  61. }