MailHelper.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  32. // 本地和测试环境目前禁止发邮件
  33. return self::sendSimpleMail($subject, $to, $config->smtp_from_mail, $content, $paramArray, $fromName);
  34. }
  35. /**
  36. * 发送短信
  37. * @param $mobile
  38. * @return null|string
  39. */
  40. public static function sendCodeSms($mobile)
  41. {
  42. //$cache = \Yii::$app->cache;
  43. $cache = \Yii::$app->redis;
  44. $lastCode = $cache->get($mobile.self::CACHE_CODE);
  45. if (!empty($lastCode)) {
  46. $time = $cache->get($mobile.self::CACHE_TIME);
  47. if ($time != null && (DateTimeHelper::microtime_float() - $time <= 120000)) {
  48. return null;
  49. }
  50. }
  51. $code = RandomHelper::getRandomNo(6);
  52. $cache->set($mobile.self::CACHE_CODE, $code);
  53. $cache->set($mobile.self::CACHE_TIME, DateTimeHelper::microtime_float());
  54. return $code;
  55. // 本地和测试环境目前禁止发短信
  56. /*
  57. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  58. $temp = self::sendBasicSms($mobile, $config->juhe_sms_tpl_id, $code);
  59. if ($temp) {
  60. $cache->set($mobile.self::CACHE_CODE, $code);
  61. $cache->set($mobile.self::CACHE_TIME, DateTimeHelper::microtime_float());
  62. return $code;
  63. } else {
  64. return null;
  65. }
  66. */
  67. }
  68. /**
  69. * 验证短信code
  70. * @param $mobile
  71. * @param $code
  72. * @return bool
  73. */
  74. public static function validSmsCode($mobile, $code)
  75. {
  76. //$cache = \Yii::$app->cache;
  77. $cache = \Yii::$app->redis;
  78. $lastCode = $cache->get($mobile.self::CACHE_CODE);
  79. if (!empty($lastCode)) {
  80. if ($lastCode != $code) {
  81. return false;
  82. } else {
  83. return true;
  84. }
  85. }
  86. return false;
  87. }
  88. /**
  89. * 发送MT4sms/RegSms
  90. * @param $mobile
  91. * @param $tplId
  92. * @param $name
  93. * @param $login
  94. * @param $pwd
  95. * @return \yii\httpclient\Response
  96. */
  97. public static function sendSms($mobile, $tplId, $name, $login, $pwd = '')
  98. {
  99. $map = new HashMapHelper();
  100. $config = Config::findOne([['id' => self::DEF_CONFIG_ID]]);
  101. $map->put('mobile', $mobile);
  102. $map->put('tpl_id', $tplId."");
  103. $tplValue = "#name#=".$name."&#login#=".$login;
  104. if ($pwd) {
  105. $tplValue .= "&#pwd#=".$pwd;
  106. }
  107. $a = urlencode("#");
  108. $b = urlencode("&");
  109. $c = urlencode("=");
  110. $tplValue = str_replace("#", $a, $tplValue);
  111. $tplValue = str_replace("&", $b, $tplValue);
  112. $tplValue = str_replace("=", $c, $tplValue);
  113. $map->put('tpl_value', $tplValue);
  114. $map->put('dtype', "json");
  115. $map->put('key', $config->juhe_sms_key);
  116. return true;
  117. $url = "http://v.juhe.cn/sms/send";
  118. $client = (new Client(['baseUrl' => $url]));
  119. $json = $client->get($url, self::buildParams($map->H_table))->send();
  120. return $json;
  121. }
  122. /**
  123. * @param string $mobile
  124. * @return array
  125. */
  126. public static function getCodeSms($mobile)
  127. {
  128. $result = [
  129. 'code' => '',
  130. 'created' => 0,
  131. ];
  132. $code = \Yii::$app->redis->get($mobile . self::CACHE_CODE);
  133. $created = \Yii::$app->redis->get($mobile . self::CACHE_TIME);
  134. if ($code && $created) {
  135. $result['code'] = $code;
  136. $result['created'] = $created;
  137. }
  138. return $result;
  139. }
  140. /**
  141. * @param $mobile
  142. * @param $tplId
  143. * @param $code
  144. * @return mixed
  145. */
  146. private static function sendBasicSms($mobile, $tplId, $code)
  147. {
  148. $map = new HashMapHelper();
  149. $config = Config::findOne([['id' => self::DEF_CONFIG_ID]]);
  150. $map->put('mobile', $mobile);
  151. $map->put('tpl_id', $tplId."");
  152. $tplValue = "#code#=".$code;
  153. $map->put('tpl_value', urlencode($tplValue));
  154. $map->put('dtype', "json");
  155. $map->put('key', $config->juhe_sms_key);
  156. $url = "http://v.juhe.cn/sms/send";
  157. $client = (new Client(['baseUrl' => $url]));
  158. $json = $client->get($url, self::buildParams($map->H_table))->send();
  159. return $json;
  160. }
  161. /**
  162. * 生成token
  163. * @param array $param
  164. * @return mixed
  165. */
  166. private static function buildParams($param)
  167. {
  168. ksort($param);//升序排序
  169. $strOauth = "";
  170. foreach ($param as $key => $val) {
  171. if ($key == 'token' || is_array($val) || $val === null) {
  172. continue;
  173. }
  174. $val = strval($val);
  175. $strOauth .= $key . '=' . $val . '&';
  176. }
  177. $strOauth = rtrim($strOauth, '&');
  178. $param['token'] = md5($strOauth);
  179. return $param;
  180. }
  181. /**
  182. * 发送简单邮件封装方法
  183. * @param $subject
  184. * @param $to
  185. * @param $from
  186. * @param $content
  187. * @param $paramArray
  188. * @param $fromName
  189. * @return bool
  190. */
  191. private static function sendSimpleMail($subject, $to, $from, $content, $paramArray, $fromName)
  192. {
  193. $isSuccess = false;
  194. $replace_content = self::replaceVariable($content, $paramArray);
  195. /*
  196. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  197. $smtp_username = $config->smtp_username;
  198. $smtp_password = $config->smtp_password;
  199. \Yii::$app->mail->apiUser = $smtp_username;
  200. \Yii::$app->mail->apiKey = $smtp_password;
  201. $result = \Yii::$app->mail->sendNormalMail($subject, '<html>'.$replace_content, [$to], $from, $fromName);
  202. if ($result['result'] === true) {
  203. self::saveRecord($result['result'], $to, $subject, $replace_content);
  204. $isSuccess = true;
  205. }
  206. */
  207. $mailid = self::saveRecord($isSuccess, $to, $subject, $replace_content);
  208. /*
  209. 配置邮箱的使用*/
  210. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]); //获取当前邮箱的配置项
  211. if($config->mail_number){
  212. $number = intval($config->mail_number);
  213. switch ($number){
  214. case 1:
  215. $smtp_username = "admin@swpartsmail1.net";
  216. $host = 'hwsmtp1.exmail.qq.com';
  217. $port = '4650';
  218. break;
  219. case 2:
  220. $smtp_username = "admin@swpartsmail2.net";
  221. $host = 'hwsmtp2.exmail.qq.com';
  222. $port = '4650';
  223. break;
  224. case 3:
  225. $smtp_username = "admin@swpartsmail3.net";
  226. $host = 'hwsmtp3.exmail.qq.com';
  227. $port = '4650';
  228. break;
  229. case 4:
  230. $smtp_username = "admin@swpartsmail4.net";
  231. $host = 'hwsmtp4.exmail.qq.com';
  232. $port = '4650';
  233. break;
  234. default:
  235. $smtp_username = "admin@swparts.net";
  236. $host = 'hwsmtp.exmail.qq.com';
  237. $port = '465';
  238. }
  239. // 设置新的邮箱地址发送
  240. Yii::$app->set('mailer', [
  241. 'class' => 'yii\swiftmailer\Mailer',
  242. 'useFileTransport' => false,
  243. 'transport' => [
  244. 'class' => 'Swift_SmtpTransport',
  245. 'host' => $host,
  246. 'username' => $smtp_username,
  247. 'password' => 'Swpartk99',
  248. 'port' => $port,
  249. 'encryption' => 'ssl',
  250. ],
  251. 'messageConfig' => [
  252. 'charset' => 'UTF-8',
  253. 'from' => [$smtp_username => 'S&W']
  254. ],
  255. ]);
  256. }
  257. $mail = \Yii::$app->mailer->compose();
  258. $mail->setTo($to);
  259. $mail->setSubject($subject);
  260. $mail->setHtmlBody( '<html>'.$replace_content);
  261. $result = $mail->send();
  262. if ($result) {
  263. $isSuccess = true;
  264. } else {
  265. Yii::warning('邮件发送失败' . VarDumper::dumpAsString($result), __METHOD__);
  266. }
  267. $status = ($isSuccess) ? 1 : 2;
  268. MailRecord::updateAll(['status' => $status], "id={$mailid}" );
  269. return $isSuccess;
  270. }
  271. /**
  272. * 将模板中的变量替换为入参
  273. * @param $content string
  274. * @param $paramArray array
  275. * @return string
  276. */
  277. public static function replaceVariable($content, $paramArray)
  278. {
  279. if (!empty($content) && !empty($paramArray)) {
  280. foreach ($paramArray as $key => $value) {
  281. $variable='${'.$key.'}';
  282. $variable1 = '#{'.$key.'}';
  283. $variable2 = '#'.$key.'#';
  284. if (is_null($value)) {
  285. continue;
  286. }
  287. while (strpos($content, $variable, 0) > -1) {
  288. $content = str_replace($variable, $value, $content);
  289. }
  290. while (strpos($content, $variable1, 0) > -1) {
  291. $content = str_replace($variable1, $value, $content);
  292. }
  293. while (strpos($content, $variable2, 0) > -1) {
  294. $content = str_replace($variable2, $value, $content);
  295. }
  296. }
  297. }
  298. return $content;
  299. }
  300. /**
  301. * 保存发送的邮件记录到crm_mail_record表
  302. * @param $status
  303. * @param $receiver
  304. * @param $subject
  305. * @param $content
  306. * @return bool
  307. */
  308. private static function saveRecord($status, $receiver, $subject, $content)
  309. {
  310. $mailRecord = new MailRecord();
  311. $mailRecord->content = $content;
  312. $mailRecord->receiver = $receiver;
  313. if ($status) {
  314. $mailRecord->status = 1;
  315. } else {
  316. $mailRecord->status = 0;
  317. }
  318. $mailRecord->subject = $subject;
  319. $mailRecord->in_time = DateTimeHelper::microtime_float();
  320. $mailRecord->save();
  321. return $mailRecord->id;
  322. }
  323. /**
  324. * 发送email邮件
  325. * @param $subject
  326. * @param $to
  327. * @param $from
  328. * @param $body
  329. * @param $mid
  330. * @return bool
  331. */
  332. public static function sendButNotSaveRecord($subject, $to, $from, $body, $mid)
  333. {
  334. $isSuccess = false;
  335. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  336. /*
  337. $smtp_username = $config->smtp_username;
  338. $smtp_password = $config->smtp_password;
  339. \Yii::$app->mail->apiUser = $smtp_username;
  340. \Yii::$app->mail->apiKey = $smtp_password;
  341. $result = \Yii::$app->mail->sendNormalMail($subject, '<html>'.$body, $to, $from);
  342. if ($result['result'] === true) {
  343. $isSuccess = true;
  344. }
  345. return $isSuccess;
  346. */
  347. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]); //获取当前邮箱的配置项
  348. if($config->mail_number){
  349. $number = intval($config->mail_number);
  350. switch ($number){
  351. case 1:
  352. $smtp_username = "admin@swpartsmail1.net";
  353. $host = 'hwsmtp1.exmail.qq.com';
  354. $port = '4650';
  355. break;
  356. case 2:
  357. $smtp_username = "admin@swpartsmail2.net";
  358. $host = 'hwsmtp2.exmail.qq.com';
  359. $port = '4650';
  360. break;
  361. case 3:
  362. $smtp_username = "admin@swpartsmail3.net";
  363. $host = 'hwsmtp3.exmail.qq.com';
  364. $port = '4650';
  365. break;
  366. case 4:
  367. $smtp_username = "admin@swpartsmail4.net";
  368. $host = 'hwsmtp4.exmail.qq.com';
  369. $port = '4650';
  370. break;
  371. default:
  372. $smtp_username = "admin@swparts.net";
  373. $host = 'hwsmtp.exmail.qq.com';
  374. $port = '465';
  375. }
  376. // 设置新的邮箱地址发送
  377. Yii::$app->set('mailer', [
  378. 'class' => 'yii\swiftmailer\Mailer',
  379. 'useFileTransport' => false,
  380. 'transport' => [
  381. 'class' => 'Swift_SmtpTransport',
  382. 'host' => $host,
  383. 'username' => $smtp_username,
  384. 'password' => 'Swpartk99',
  385. 'port' => $port,
  386. 'encryption' => 'ssl',
  387. ],
  388. 'messageConfig' => [
  389. 'charset' => 'UTF-8',
  390. 'from' => [$smtp_username => 'S&W']
  391. ],
  392. ]);
  393. }
  394. $mail = \Yii::$app->mailer->compose();
  395. $mail->setTo($to);
  396. $mail->setSubject($subject);
  397. $mail->setHtmlBody( '<html>'.$body);
  398. if ($mail->send()) {
  399. MailRecord::updateAll(['status' => 1], "id={$mid}" );
  400. return true;
  401. }
  402. return false;
  403. }
  404. }