MailHelper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: chenkuan
  5. * Date: 2017/11/13
  6. * Time: 下午1:54
  7. */
  8. namespace backend\helpers;
  9. use backend\models\Config;
  10. use backend\models\MailRecord;
  11. use common\helpers\HashMapHelper;
  12. use yii\helpers\VarDumper;
  13. use yii\httpclient\Client;
  14. use Yii;
  15. class MailHelper
  16. {
  17. const DEF_CONFIG_ID = 1;
  18. const CACHE_CODE = 'cache_code';
  19. const CACHE_TIME = 'cache_time';
  20. /**
  21. * 发送简单邮件
  22. * @param string $subject 主题/标题 如:'找回密码验证'
  23. * @param string $to 接收方邮箱地址
  24. * @param array $paramArray 需要替换的模版内容参数,如:找回密码中的${code} 数组传递['code' => $code]
  25. * @param string $fromName 发送人姓名
  26. * @param string $content 内容模板
  27. * @return bool 成功/失败
  28. */
  29. public static function sendMail($subject, $to, $paramArray, $fromName, $content)
  30. {
  31. $cache = \Yii::$app->cache;
  32. $config = $cache->get('config');
  33. if ($config == null) {
  34. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  35. $cache->set('config', $config, 86400);
  36. }
  37. // 本地和测试环境目前禁止发邮件
  38. return self::sendSimpleMail($subject, $to, $config->smtp_from_mail, $content, $paramArray, $fromName);
  39. }
  40. /**
  41. * 发送短信
  42. * @param $mobile
  43. * @return null|string
  44. */
  45. public static function sendCodeSms($mobile)
  46. {
  47. $cache = \Yii::$app->cache;
  48. $lastCode = $cache->get($mobile.self::CACHE_CODE);
  49. if (!empty($lastCode)) {
  50. $time = $cache->get($mobile.self::CACHE_TIME);
  51. if ($time != null && (DateTimeHelper::microtime_float() - $time <= 120000)) {
  52. return null;
  53. }
  54. }
  55. $code = RandomHelper::getRandomNo(6);
  56. $cache->set($mobile.self::CACHE_CODE, $code);
  57. $cache->set($mobile.self::CACHE_TIME, DateTimeHelper::microtime_float());
  58. return $code;
  59. // 本地和测试环境目前禁止发短信
  60. /*
  61. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  62. $temp = self::sendBasicSms($mobile, $config->juhe_sms_tpl_id, $code);
  63. if ($temp) {
  64. $cache->set($mobile.self::CACHE_CODE, $code);
  65. $cache->set($mobile.self::CACHE_TIME, DateTimeHelper::microtime_float());
  66. return $code;
  67. } else {
  68. return null;
  69. }
  70. */
  71. }
  72. /**
  73. * 验证短信code
  74. * @param $mobile
  75. * @param $code
  76. * @return bool
  77. */
  78. public static function validSmsCode($mobile, $code)
  79. {
  80. $cache = \Yii::$app->cache;
  81. $lastCode = $cache->get($mobile.self::CACHE_CODE);
  82. if (!empty($lastCode)) {
  83. if ($lastCode != $code) {
  84. return false;
  85. } else {
  86. return true;
  87. }
  88. }
  89. return false;
  90. }
  91. /**
  92. * 发送MT4sms/RegSms
  93. * @param $mobile
  94. * @param $tplId
  95. * @param $name
  96. * @param $login
  97. * @param $pwd
  98. * @return \yii\httpclient\Response
  99. */
  100. public static function sendSms($mobile, $tplId, $name, $login, $pwd = '')
  101. {
  102. $map = new HashMapHelper();
  103. $config = Config::findOne([['id' => self::DEF_CONFIG_ID]]);
  104. $map->put('mobile', $mobile);
  105. $map->put('tpl_id', $tplId."");
  106. $tplValue = "#name#=".$name."&#login#=".$login;
  107. if ($pwd) {
  108. $tplValue .= "&#pwd#=".$pwd;
  109. }
  110. $a = urlencode("#");
  111. $b = urlencode("&");
  112. $c = urlencode("=");
  113. $tplValue = str_replace("#", $a, $tplValue);
  114. $tplValue = str_replace("&", $b, $tplValue);
  115. $tplValue = str_replace("=", $c, $tplValue);
  116. $map->put('tpl_value', $tplValue);
  117. $map->put('dtype', "json");
  118. $map->put('key', $config->juhe_sms_key);
  119. return true;
  120. $url = "http://v.juhe.cn/sms/send";
  121. $client = (new Client(['baseUrl' => $url]));
  122. $json = $client->get($url, self::buildParams($map->H_table))->send();
  123. return $json;
  124. }
  125. /**
  126. * @param string $mobile
  127. * @return array
  128. */
  129. public static function getCodeSms($mobile)
  130. {
  131. $result = [
  132. 'code' => '',
  133. 'created' => 0,
  134. ];
  135. $code = \Yii::$app->getCache()->get($mobile . self::CACHE_CODE);
  136. $created = \Yii::$app->getCache()->get($mobile . self::CACHE_TIME);
  137. if ($code && $created) {
  138. $result['code'] = $code;
  139. $result['created'] = $created;
  140. }
  141. return $result;
  142. }
  143. /**
  144. * @param $mobile
  145. * @param $tplId
  146. * @param $code
  147. * @return mixed
  148. */
  149. private static function sendBasicSms($mobile, $tplId, $code)
  150. {
  151. $map = new HashMapHelper();
  152. $config = Config::findOne([['id' => self::DEF_CONFIG_ID]]);
  153. $map->put('mobile', $mobile);
  154. $map->put('tpl_id', $tplId."");
  155. $tplValue = "#code#=".$code;
  156. $map->put('tpl_value', urlencode($tplValue));
  157. $map->put('dtype', "json");
  158. $map->put('key', $config->juhe_sms_key);
  159. $url = "http://v.juhe.cn/sms/send";
  160. $client = (new Client(['baseUrl' => $url]));
  161. $json = $client->get($url, self::buildParams($map->H_table))->send();
  162. return $json;
  163. }
  164. /**
  165. * 生成token
  166. * @param array $param
  167. * @return mixed
  168. */
  169. private static function buildParams($param)
  170. {
  171. ksort($param);//升序排序
  172. $strOauth = "";
  173. foreach ($param as $key => $val) {
  174. if ($key == 'token' || is_array($val) || $val === null) {
  175. continue;
  176. }
  177. $val = strval($val);
  178. $strOauth .= $key . '=' . $val . '&';
  179. }
  180. $strOauth = rtrim($strOauth, '&');
  181. $param['token'] = md5($strOauth);
  182. return $param;
  183. }
  184. /**
  185. * 发送简单邮件封装方法
  186. * @param $subject
  187. * @param $to
  188. * @param $from
  189. * @param $content
  190. * @param $paramArray
  191. * @param $fromName
  192. * @return bool
  193. */
  194. private static function sendSimpleMail($subject, $to, $from, $content, $paramArray, $fromName)
  195. {
  196. $isSuccess = false;
  197. $replace_content = self::replaceVariable($content, $paramArray);
  198. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  199. /*
  200. $smtp_username = $config->smtp_username;
  201. $smtp_password = $config->smtp_password;
  202. \Yii::$app->mail->apiUser = $smtp_username;
  203. \Yii::$app->mail->apiKey = $smtp_password;
  204. $result = \Yii::$app->mail->sendNormalMail($subject, '<html>'.$replace_content, [$to], $from, $fromName);
  205. if ($result['result'] === true) {
  206. self::saveRecord($result['result'], $to, $subject, $replace_content);
  207. $isSuccess = true;
  208. }
  209. */
  210. $mailid = self::saveRecord($isSuccess, $to, $subject, $replace_content);
  211. $mail = \Yii::$app->mailer->compose();
  212. $mail->setTo($to);
  213. $mail->setSubject($subject);
  214. $mail->setHtmlBody( '<html>'.$replace_content);
  215. $result = $mail->send();
  216. if ($result) {
  217. $isSuccess = true;
  218. } else {
  219. Yii::warning('邮件发送失败' . VarDumper::dumpAsString($result), __METHOD__);
  220. }
  221. $status = ($isSuccess) ? 1 : 2;
  222. MailRecord::updateAll(['status' => $status], "id={$mailid}" );
  223. return $isSuccess;
  224. }
  225. /**
  226. * 将模板中的变量替换为入参
  227. * @param $content string
  228. * @param $paramArray array
  229. * @return string
  230. */
  231. public static function replaceVariable($content, $paramArray)
  232. {
  233. if (!empty($content) && !empty($paramArray)) {
  234. foreach ($paramArray as $key => $value) {
  235. $variable='${'.$key.'}';
  236. $variable1 = '#{'.$key.'}';
  237. $variable2 = '#'.$key.'#';
  238. if (is_null($value)) {
  239. continue;
  240. }
  241. while (strpos($content, $variable, 0) > -1) {
  242. $content = str_replace($variable, $value, $content);
  243. }
  244. while (strpos($content, $variable1, 0) > -1) {
  245. $content = str_replace($variable1, $value, $content);
  246. }
  247. while (strpos($content, $variable2, 0) > -1) {
  248. $content = str_replace($variable2, $value, $content);
  249. }
  250. }
  251. }
  252. return $content;
  253. }
  254. /**
  255. * 保存发送的邮件记录到crm_mail_record表
  256. * @param $status
  257. * @param $receiver
  258. * @param $subject
  259. * @param $content
  260. * @return bool
  261. */
  262. private static function saveRecord($status, $receiver, $subject, $content)
  263. {
  264. $mailRecord = new MailRecord();
  265. $mailRecord->content = $content;
  266. $mailRecord->receiver = $receiver;
  267. if ($status) {
  268. $mailRecord->status = 1;
  269. } else {
  270. $mailRecord->status = 0;
  271. }
  272. $mailRecord->subject = $subject;
  273. $mailRecord->in_time = DateTimeHelper::microtime_float();
  274. $mailRecord->save();
  275. return $mailRecord->id;
  276. }
  277. /**
  278. * 发送email邮件
  279. * @param $subject
  280. * @param $to
  281. * @param $from
  282. * @param $body
  283. * @param $mid
  284. * @return bool
  285. */
  286. public static function sendButNotSaveRecord($subject, $to, $from, $body, $mid)
  287. {
  288. $isSuccess = false;
  289. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  290. /*
  291. $smtp_username = $config->smtp_username;
  292. $smtp_password = $config->smtp_password;
  293. \Yii::$app->mail->apiUser = $smtp_username;
  294. \Yii::$app->mail->apiKey = $smtp_password;
  295. $result = \Yii::$app->mail->sendNormalMail($subject, '<html>'.$body, $to, $from);
  296. if ($result['result'] === true) {
  297. $isSuccess = true;
  298. }
  299. return $isSuccess;
  300. */
  301. $mail = \Yii::$app->mailer->compose();
  302. $mail->setTo($to);
  303. $mail->setSubject($subject);
  304. $mail->setHtmlBody( '<html>'.$body);
  305. if ($mail->send()) {
  306. MailRecord::updateAll(['status' => 1], "id={$mid}" );
  307. return true;
  308. }
  309. return false;
  310. }
  311. }