MailCaptcha.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\service\passport;
  13. use think\facade\Log;
  14. use yiovo\cache\facade\Cache;
  15. use yiovo\captcha\facade\CaptchaApi;
  16. use app\api\validate\passport\EmailCaptcha as ValidateEmailCaptcha;
  17. use app\common\service\BaseService;
  18. use cores\exception\BaseException;
  19. use PHPMailer\PHPMailer\PHPMailer;
  20. use PHPMailer\PHPMailer\SMTP;
  21. use PHPMailer\PHPMailer\Exception;
  22. /**
  23. * 服务类:发送邮箱验证码
  24. * Class MailCaptcha
  25. * @package app\api\service\passport
  26. */
  27. class MailCaptcha extends BaseService
  28. {
  29. // 最大发送次数,默认10次
  30. protected int $sendTimes = 10;
  31. // 发送限制间隔时间,默认24小时
  32. protected int $safeTime = 86400;
  33. /**
  34. * 发送邮件验证码
  35. * @param array $data
  36. * @return bool
  37. * @throws BaseException
  38. */
  39. public function handle(array $data): bool
  40. {
  41. // 数据验证
  42. $this->validate($data);
  43. // 执行发送短信
  44. if (!$this->sendCaptcha($data['email'])) {
  45. return false;
  46. }
  47. return true;
  48. }
  49. /**
  50. * 执行发送邮箱验证码
  51. * @param string $email
  52. * @return bool
  53. */
  54. public function sendCaptcha(string $email): bool
  55. {
  56. // 缓存发送记录并判断次数
  57. if (!$this->record($email)) {
  58. return false;
  59. }
  60. // 生成验证码
  61. $smsCaptcha = CaptchaApi::createSMS($email);
  62. $mail = new PHPMailer(true);
  63. try {
  64. //Server settings
  65. $mail->SMTPDebug = SMTP::DEBUG_SERVER;//DEBUG_OFF //Enable verbose debug output
  66. $mail->SMTPOptions = array(
  67. 'ssl' => array(
  68. 'verify_peer' => false,
  69. 'verify_peer_name' => false,
  70. 'allow_self_signed' => true
  71. )
  72. );
  73. $mail->isSMTP(); //Send using SMTP
  74. $mail->Host = 'smtp.163.com'; //Set the SMTP server to send through
  75. $mail->SMTPAuth = true; //Enable SMTP authentication
  76. $mail->Username = 'zhangdehua814@163.com'; //SMTP username
  77. $mail->Password = 'SGPMIQCKVKGIJUGQ'; //SMTP password
  78. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
  79. $mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
  80. //Recipients
  81. $mail->setFrom('zhangdehua814@163.com', 'Mailer');
  82. $mail->addAddress($email, 'Gold'); //Add a recipient
  83. //$mail->addAddress('ellen@example.com'); //Name is optional
  84. //$mail->addReplyTo('info@example.com', 'Information');
  85. //$mail->addCC('cc@example.com');
  86. //$mail->addBCC('bcc@example.com');
  87. //Attachments
  88. //$mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
  89. //$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name
  90. //Content
  91. //$mail->isHTML(true); //Set email format to HTML
  92. $mail->Subject = 'Captcha';
  93. $mail->Body = 'Your captcha is ' . $smsCaptcha['code'] . '.Please use it in 15 minutes';
  94. $mail->AltBody = 'This is the Your captcha for vapes';
  95. $mail->send();
  96. //echo 'Message has been sent';
  97. } catch (Exception $e) {
  98. //echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  99. Log::error(__CLASS__ . ':' . __METHOD__ . $e->getMessage() . '---' . $mail->ErrorInfo);
  100. Log::error(__CLASS__ . ':' . __METHOD__, ['errMsg' => $e->getMessage(), 'mailError' => $mail->ErrorInfo]);
  101. return false;
  102. }
  103. return true;
  104. }
  105. /**
  106. * 发送营销文本邮件
  107. * @param string $email
  108. * @param string $subject
  109. * @param string $body
  110. * @param string $altBody
  111. * @param bool $isHtml
  112. * @param string $name
  113. * @return bool
  114. */
  115. public function sendText(string $email, string $subject = '', string $body = '', string $altBody = '', bool $isHtml = false, string $name = 'vip'): bool
  116. {
  117. $mail = new PHPMailer(true);
  118. try {
  119. //Server settings
  120. $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
  121. $mail->isSMTP(); //Send using SMTP
  122. $mail->Host = 'smtp.163.com'; //Set the SMTP server to send through
  123. $mail->SMTPAuth = true; //Enable SMTP authentication
  124. $mail->Username = 'zhangdehua814@163.com'; //SMTP username
  125. $mail->Password = 'SGPMIQCKVKGIJUGQ'; //SMTP password
  126. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
  127. $mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
  128. //Recipients
  129. $mail->setFrom('zhangdehua814@163.com', 'Mailer');
  130. $mail->addAddress($email, $name); //Add a recipient
  131. //Content
  132. if ($isHtml) {
  133. $mail->isHTML(true); //Set email format to HTML
  134. }
  135. $mail->Subject = $subject;
  136. $mail->Body = $body;
  137. if (!empty($altBody)) {
  138. $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
  139. }
  140. $mail->send();
  141. echo 'Message has been sent';
  142. } catch (Exception $e) {
  143. echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  144. Log::error(__CLASS__ . ':' . __METHOD__, ['errMsg' => $e->getMessage(), 'mailError' => $mail->ErrorInfo]);
  145. return false;
  146. }
  147. return true;
  148. }
  149. /**
  150. * 记录短信验证码发送记录并判断是否超出发送限制
  151. * @param string $mobile
  152. * @return bool
  153. */
  154. private function record(string $email): bool
  155. {
  156. // 获取发送记录缓存
  157. $record = Cache::get("sendCaptchaEmail.$email");
  158. // 写入缓存:记录剩余发送次数
  159. if (empty($record)) {
  160. Cache::set("sendCaptchaEmail.$email", ['times' => $this->sendTimes - 1], $this->safeTime);
  161. return true;
  162. }
  163. // 判断发送次数是否合法
  164. if ($record['times'] <= 0) {
  165. $this->error = '很抱歉,已超出今日最大发送次数限制';
  166. return false;
  167. }
  168. // 发送次数递减
  169. Cache::update("sendCaptchaEmail.$email", ['times' => $record['times'] - 1]);
  170. return true;
  171. }
  172. /**
  173. * 数据验证
  174. * @param array $data
  175. * @throws BaseException
  176. */
  177. public function validate(array $data)
  178. {
  179. // 数据验证
  180. $validate = new ValidateEmailCaptcha;
  181. if (!$validate->check($data)) {
  182. throwError($validate->getError());
  183. }
  184. // 验证图形验证码
  185. // if (!CaptchaApi::check($data['captchaCode'], $data['captchaKey'])) {
  186. // throwError('很抱歉,图形验证码不正确');
  187. // }
  188. }
  189. public function checkCaptcha($captchaCode = '', $email = '')
  190. {
  191. $localCode = Cache::get('captchaSMS.' . $email);
  192. if (empty($localCode) || empty($localCode['code']) || $localCode['code'] != $captchaCode) {
  193. throwError('Sorry,your captcha is invalid');
  194. }
  195. }
  196. }