EmailService.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Modules\Mini\Services;
  3. use App\Base\BaseService;
  4. use App\Exceptions\ClientException;
  5. use App\Mail\ForgetPasswordEmail;
  6. use App\Mail\RegisterEmail;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\Mail;
  9. class EmailService extends BaseService
  10. {
  11. public function emailCaptcha($email, $source)
  12. {
  13. switch ($source) {
  14. case "register":
  15. return $this->register($email);
  16. case "forgetPassword":
  17. return $this->forgetPassword($email);
  18. default:
  19. throw new ClientException("source未匹配");
  20. }
  21. }
  22. private function register($email): bool
  23. {
  24. $captcha = Cache::remember("email:registerCaptcha" . $email, 10, function () {
  25. return rand(100000, 999999);
  26. });
  27. try {
  28. Mail::to($email)->send(new RegisterEmail($captcha));
  29. } catch (\Exception $e) {
  30. logger()->error("邮件发送失败 " . $e->getMessage());
  31. throw new ClientException("邮件发送失败,请稍后再试");
  32. }
  33. return true;
  34. }
  35. private function forgetPassword($email): bool
  36. {
  37. $captcha = Cache::remember("email:forgetPasswordCaptcha" . $email, 10, function () {
  38. return rand(100000, 999999);
  39. });
  40. try {
  41. Mail::to($email)->send(new ForgetPasswordEmail($captcha));
  42. } catch (\Exception $e) {
  43. logger()->error("邮件发送失败 " . $e->getMessage());
  44. throw new ClientException("邮件发送失败,请稍后再试");
  45. }
  46. return true;
  47. }
  48. }