MailHelper.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: User
  5. * Date: 2019/6/19
  6. * Time: 下午 5:03
  7. */
  8. namespace backend\helpers;
  9. use backend\models\Config;
  10. use backend\models\MailRecord;
  11. use backend\models\MailConfig;
  12. use common\helpers\HashMapHelper;
  13. use yii\helpers\VarDumper;
  14. use yii\httpclient\Client;
  15. use Yii;
  16. class MailHelper
  17. {
  18. const DEF_CONFIG_ID = 1;
  19. const CACHE_CODE = 'cache_code';
  20. const CACHE_TIME = 'cache_time';
  21. /**
  22. * 发送简单邮件
  23. * @param string $subject 主题/标题 如:'找回密码验证'
  24. * @param string $to 接收方邮箱地址
  25. * @param array $paramArray 需要替换的模版内容参数,如:找回密码中的${code} 数组传递['code' => $code]
  26. * @param string $fromName 发送人姓名
  27. * @param string $content 内容模板
  28. * @return bool 成功/失败
  29. */
  30. public static function sendMail($subject, $to, $paramArray, $fromName, $content)
  31. {
  32. $cache = \Yii::$app->cache;
  33. $config = $cache->get('config');
  34. if ($config == null) {
  35. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  36. $cache->set('config', $config, 86400);
  37. }
  38. // 本地和测试环境目前禁止发邮件
  39. return self::sendSimpleMail($subject, $to, $config->smtp_from_mail, $content, $paramArray, $fromName);
  40. }
  41. /**
  42. * 发送短信
  43. * @param $mobile
  44. * @return null|string
  45. */
  46. public static function sendCodeSms($mobile)
  47. {
  48. $cache = \Yii::$app->cache;
  49. $lastCode = $cache->get($mobile.self::CACHE_CODE);
  50. if (!empty($lastCode)) {
  51. $time = $cache->get($mobile.self::CACHE_TIME);
  52. if ($time != null && (DateTimeHelper::microtime_float() - $time <= 120000)) {
  53. return null;
  54. }
  55. }
  56. $code = RandomHelper::getRandomNo(6);
  57. $cache->set($mobile.self::CACHE_CODE, $code);
  58. $cache->set($mobile.self::CACHE_TIME, DateTimeHelper::microtime_float());
  59. return $code;
  60. // 本地和测试环境目前禁止发短信
  61. /*
  62. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  63. $temp = self::sendBasicSms($mobile, $config->juhe_sms_tpl_id, $code);
  64. if ($temp) {
  65. $cache->set($mobile.self::CACHE_CODE, $code);
  66. $cache->set($mobile.self::CACHE_TIME, DateTimeHelper::microtime_float());
  67. return $code;
  68. } else {
  69. return null;
  70. }
  71. */
  72. }
  73. /**
  74. * 验证短信code
  75. * @param $mobile
  76. * @param $code
  77. * @return bool
  78. */
  79. public static function validSmsCode($mobile, $code)
  80. {
  81. $cache = \Yii::$app->cache;
  82. $lastCode = $cache->get($mobile.self::CACHE_CODE);
  83. if (!empty($lastCode)) {
  84. if ($lastCode != $code) {
  85. return false;
  86. } else {
  87. return true;
  88. }
  89. }
  90. return false;
  91. }
  92. /**
  93. * 发送MT4sms/RegSms
  94. * @param $mobile
  95. * @param $tplId
  96. * @param $name
  97. * @param $login
  98. * @param $pwd
  99. * @return \yii\httpclient\Response
  100. */
  101. public static function sendSms($mobile, $tplId, $name, $login, $pwd = '')
  102. {
  103. $map = new HashMapHelper();
  104. $config = Config::findOne([['id' => self::DEF_CONFIG_ID]]);
  105. $map->put('mobile', $mobile);
  106. $map->put('tpl_id', $tplId."");
  107. $tplValue = "#name#=".$name."&#login#=".$login;
  108. if ($pwd) {
  109. $tplValue .= "&#pwd#=".$pwd;
  110. }
  111. $a = urlencode("#");
  112. $b = urlencode("&");
  113. $c = urlencode("=");
  114. $tplValue = str_replace("#", $a, $tplValue);
  115. $tplValue = str_replace("&", $b, $tplValue);
  116. $tplValue = str_replace("=", $c, $tplValue);
  117. $map->put('tpl_value', $tplValue);
  118. $map->put('dtype', "json");
  119. $map->put('key', $config->juhe_sms_key);
  120. return true;
  121. $url = "http://v.juhe.cn/sms/send";
  122. $client = (new Client(['baseUrl' => $url]));
  123. $json = $client->get($url, self::buildParams($map->H_table))->send();
  124. return $json;
  125. }
  126. /**
  127. * @param string $mobile
  128. * @return array
  129. */
  130. public static function getCodeSms($mobile)
  131. {
  132. $result = [
  133. 'code' => '',
  134. 'created' => 0,
  135. ];
  136. $code = \Yii::$app->getCache()->get($mobile . self::CACHE_CODE);
  137. $created = \Yii::$app->getCache()->get($mobile . self::CACHE_TIME);
  138. if ($code && $created) {
  139. $result['code'] = $code;
  140. $result['created'] = $created;
  141. }
  142. return $result;
  143. }
  144. /**
  145. * @param $mobile
  146. * @param $tplId
  147. * @param $code
  148. * @return mixed
  149. */
  150. private static function sendBasicSms($mobile, $tplId, $code)
  151. {
  152. $map = new HashMapHelper();
  153. $config = Config::findOne([['id' => self::DEF_CONFIG_ID]]);
  154. $map->put('mobile', $mobile);
  155. $map->put('tpl_id', $tplId."");
  156. $tplValue = "#code#=".$code;
  157. $map->put('tpl_value', urlencode($tplValue));
  158. $map->put('dtype', "json");
  159. $map->put('key', $config->juhe_sms_key);
  160. $url = "http://v.juhe.cn/sms/send";
  161. $client = (new Client(['baseUrl' => $url]));
  162. $json = $client->get($url, self::buildParams($map->H_table))->send();
  163. return $json;
  164. }
  165. /**
  166. * 生成token
  167. * @param array $param
  168. * @return mixed
  169. */
  170. private static function buildParams($param)
  171. {
  172. ksort($param);//升序排序
  173. $strOauth = "";
  174. foreach ($param as $key => $val) {
  175. if ($key == 'token' || is_array($val) || $val === null) {
  176. continue;
  177. }
  178. $val = strval($val);
  179. $strOauth .= $key . '=' . $val . '&';
  180. }
  181. $strOauth = rtrim($strOauth, '&');
  182. $param['token'] = md5($strOauth);
  183. return $param;
  184. }
  185. /**
  186. * 发送简单邮件封装方法
  187. * @param $subject
  188. * @param $to
  189. * @param $from
  190. * @param $content
  191. * @param $paramArray
  192. * @param $fromName
  193. * @return bool
  194. */
  195. private static function sendSimpleMail($subject, $to, $from, $content, $paramArray, $fromName)
  196. {
  197. $isSuccess = false;
  198. $replace_content = self::replaceVariable($content, $paramArray);
  199. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  200. $mailConfig = new MailConfig();
  201. $configArr = $mailConfig->getMailConfig($to);
  202. if(!$configArr){
  203. $connection=Yii::$app->db;
  204. $time = time() - 300;
  205. //将5分钟内发送给相同收件人和相同主题的发件记录设置为不可发送状态
  206. $sql = "update crm_mail_record set status = 2 where subject = '$subject' and receiver = '$to' and in_time > $time";
  207. $command=$connection->createCommand($sql);
  208. $rowCount=$command->execute();
  209. }else{
  210. Yii::$app->set('mailer', [
  211. 'class' => 'yii\swiftmailer\Mailer',
  212. 'useFileTransport' => false,
  213. 'transport' => [
  214. 'class' => 'Swift_SmtpTransport',
  215. 'host' => $configArr['host'],
  216. 'username' => $configArr['smtp_username'],
  217. 'password' => $configArr['password'],
  218. 'port' => $configArr['port'],
  219. 'encryption' => 'ssl',
  220. ],
  221. 'messageConfig' => [
  222. 'charset' => 'UTF-8',
  223. 'from' => [$configArr['send_mail'] => 'Noryatai']
  224. ],
  225. ]);
  226. }
  227. $mailid = self::saveRecord($isSuccess, $to, $subject, $replace_content,$configArr['id']);
  228. //如果是订单信息就开始设置为paycenter的邮箱地址发送
  229. if($subject=="訂單信息"){
  230. $pay_mail_num = intval($config->pay_mail_num);
  231. if($pay_mail_num == 0){
  232. $smtp_username = "admin@fastpaypro.net";
  233. $host = 'hwsmtppay.exmail.qq.com';
  234. $port = '4650';
  235. // 设置新的邮箱地址发送
  236. Yii::$app->set('mailer', [
  237. 'class' => 'yii\swiftmailer\Mailer',
  238. 'useFileTransport' => false,
  239. 'transport' => [
  240. 'class' => 'Swift_SmtpTransport',
  241. 'host' => $host,
  242. 'username' => $smtp_username,
  243. 'password' => 'Fastpak99',
  244. 'port' => $port,
  245. 'encryption' => 'ssl',
  246. ],
  247. 'messageConfig' => [
  248. 'charset' => 'UTF-8',
  249. 'from' => [$smtp_username => 'fastpaypro']
  250. ],
  251. ]);
  252. }else{
  253. $pay_mail = $config->pay_mail;
  254. $smtp_username = "apikey";
  255. $host = 'smtp.sendgrid.net';
  256. $port = '465';
  257. // 设置新的邮箱地址发送
  258. Yii::$app->set('mailer', [
  259. 'class' => 'yii\swiftmailer\Mailer',
  260. 'useFileTransport' => false,
  261. 'transport' => [
  262. 'class' => 'Swift_SmtpTransport',
  263. 'host' => $host,
  264. 'username' => $smtp_username,
  265. 'password' => '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',
  266. 'port' => $port,
  267. 'encryption' => 'ssl',
  268. ],
  269. 'messageConfig' => [
  270. 'charset' => 'UTF-8',
  271. 'from' => [$pay_mail => $pay_mail]
  272. ],
  273. ]);
  274. }
  275. }
  276. $mail = \Yii::$app->mailer->compose();
  277. $mail->setTo($to);
  278. $mail->setSubject($subject);
  279. $mail->setHtmlBody( '<html>'.$replace_content);
  280. $result = $mail->send();
  281. if ($result) {
  282. $isSuccess = true;
  283. } else {
  284. self::sendSimpleMail($subject, $to, $from, $content, $paramArray, $fromName);
  285. Yii::warning('邮件发送失败' . VarDumper::dumpAsString($result), __METHOD__);
  286. }
  287. $status = ($isSuccess) ? 1 : 2;
  288. MailRecord::updateAll(['status' => $status], "id={$mailid}" );
  289. return $isSuccess;
  290. }
  291. /**
  292. * 将模板中的变量替换为入参
  293. * @param $content string
  294. * @param $paramArray array
  295. * @return string
  296. */
  297. public static function replaceVariable($content, $paramArray)
  298. {
  299. if (!empty($content) && !empty($paramArray)) {
  300. foreach ($paramArray as $key => $value) {
  301. $variable='${'.$key.'}';
  302. $variable1 = '#{'.$key.'}';
  303. $variable2 = '#'.$key.'#';
  304. if (is_null($value)) {
  305. continue;
  306. }
  307. while (strpos($content, $variable, 0) > -1) {
  308. $content = str_replace($variable, $value, $content);
  309. }
  310. while (strpos($content, $variable1, 0) > -1) {
  311. $content = str_replace($variable1, $value, $content);
  312. }
  313. while (strpos($content, $variable2, 0) > -1) {
  314. $content = str_replace($variable2, $value, $content);
  315. }
  316. }
  317. }
  318. return $content;
  319. }
  320. /**
  321. * 保存发送的邮件记录到crm_mail_record表
  322. * @param $status
  323. * @param $receiver
  324. * @param $subject
  325. * @param $content
  326. * @return bool
  327. */
  328. private static function saveRecord($status, $receiver, $subject, $content,$num)
  329. {
  330. $mailRecord = new MailRecord();
  331. $mailRecord->content = $content;
  332. $mailRecord->receiver = $receiver;
  333. if ($status) {
  334. $mailRecord->status = 1;
  335. } else {
  336. $mailRecord->status = 0;
  337. }
  338. $mailRecord->subject = $subject;
  339. $mailRecord->in_time = DateTimeHelper::microtime_float();
  340. $mailRecord->mail_num = $num;
  341. $mailRecord->save();
  342. return $mailRecord->id;
  343. }
  344. /**
  345. * 发送email邮件
  346. * @param $subject
  347. * @param $to
  348. * @param $from
  349. * @param $body
  350. * @param $mid
  351. * @return bool
  352. */
  353. public static function sendButNotSaveRecord($subject, $to, $from, $body, $mid)
  354. {
  355. $isSuccess = false;
  356. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  357. /*
  358. $smtp_username = $config->smtp_username;
  359. $smtp_password = $config->smtp_password;
  360. \Yii::$app->mail->apiUser = $smtp_username;
  361. \Yii::$app->mail->apiKey = $smtp_password;
  362. $result = \Yii::$app->mail->sendNormalMail($subject, '<html>'.$body, $to, $from);
  363. if ($result['result'] === true) {
  364. $isSuccess = true;
  365. }
  366. return $isSuccess;
  367. */
  368. $mailConfig = new MailConfig();
  369. $configArr = $mailConfig->getMailConfig($to);
  370. if(!$configArr){
  371. $connection=Yii::$app->db;
  372. $time = time() - 300;
  373. //将5分钟内发送给相同收件人和相同主题的发件记录设置为不可发送状态
  374. $sql = "update crm_mail_record set status = 2 where subject = '$subject' and receiver = '$to' and in_time > $time";
  375. $command=$connection->createCommand($sql);
  376. $rowCount=$command->execute();
  377. return false;
  378. }else{
  379. $transport = [
  380. 'class' => 'Swift_SmtpTransport',
  381. 'host' => $configArr['host'],
  382. 'username' => $configArr['smtp_username'],
  383. 'password' => $configArr['password'],
  384. 'port' => $configArr['port'],
  385. 'encryption' => 'ssl',
  386. ];
  387. if($configArr['port'] == 587){
  388. $transport['encryption'] = 'tls';
  389. }else{
  390. $transport['encryption'] = 'ssl';
  391. }
  392. Yii::$app->set('mailer', [
  393. 'class' => 'yii\swiftmailer\Mailer',
  394. 'useFileTransport' => false,
  395. 'transport' => $transport,
  396. 'messageConfig' => [
  397. 'charset' => 'UTF-8',
  398. 'from' => [$configArr['send_mail'] => 'Noryatai']
  399. ],
  400. ]);
  401. }
  402. // 配置邮箱的使用
  403. // if($config->mail_number){
  404. // $number = intval($config->mail_number);
  405. // switch ($number){
  406. // case 1:
  407. // $smtp_username = "admin@notify-online.com";
  408. // $host = 'hwsmtp1.exmail.qq.com';
  409. // $password="Notifk99";
  410. // $port = '4650';
  411. // break;
  412. // case 2:
  413. // $smtp_username = "admin@notify2-online.com";
  414. // $host = 'hwsmtp2.exmail.qq.com';
  415. // $password="Notifk99";
  416. // $port = '4650';
  417. // break;
  418. // case 3:
  419. // $smtp_username = "admin@notify3-online.com";
  420. // $host = 'hwsmtp3.exmail.qq.com';
  421. // $password="Notifk99";
  422. // $port = '4650';
  423. // break;
  424. // case 4:
  425. // $smtp_username = "admin@notify4-online.com";
  426. // $host = 'hwsmtp4.exmail.qq.com';
  427. // $password="Notifk99";
  428. // $port = '4650';
  429. // break;
  430. // case 5:
  431. // $smtp_username = "info@Noryataimkt.com";
  432. // $host = 'smtp.fastmail.com';
  433. // $password="q7yka9tdhgym9zuy";
  434. // $port = '465';
  435. // break;
  436. // case 6:
  437. // $smtp_username = "info2@Noryataimkt.com";
  438. // $host = 'smtp.fastmail.com';
  439. // $password="4emg7ux97qxz4fc7";
  440. // $port = '465';
  441. // break;
  442. // case 7:
  443. // $pay_mail = "adminemail1@Noryataimkt.com";
  444. // $smtp_username = "apikey";
  445. // $host = 'smtp.sendgrid.net';
  446. // $password="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";
  447. // $port = '465';
  448. // break;
  449. // case 8:
  450. // $pay_mail = "adminemail2@Noryataimkt.com";
  451. // $smtp_username = "apikey";
  452. // $host = 'smtp.sendgrid.net';
  453. // $password="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";
  454. // $port = '465';
  455. // break;
  456. // case 9:
  457. // $pay_mail = "adminemail3@Noryataimkt.com";
  458. // $smtp_username = "apikey";
  459. // $host = 'smtp.sendgrid.net';
  460. // $password="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";
  461. // $port = '465';
  462. // break;
  463. // case 10:
  464. // $pay_mail = "adminemail4@Noryataimkt.com";
  465. // $smtp_username = "apikey";
  466. // $host = 'smtp.sendgrid.net';
  467. // $password="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";
  468. // $port = '465';
  469. // break;
  470. // default:
  471. // $pay_mail = "admin@Noryataimkt.com";
  472. // $smtp_username = "apikey";
  473. // $host = 'smtp.sendgrid.net';
  474. // $password="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";
  475. // $port = '465';
  476. // }
  477. // if($number==999 || $number==7 || $number==8 || $number==9 || $number==10){
  478. // // 设置新的邮箱地址发送
  479. // Yii::$app->set('mailer', [
  480. // 'class' => 'yii\swiftmailer\Mailer',
  481. // 'useFileTransport' => false,
  482. // 'transport' => [
  483. // 'class' => 'Swift_SmtpTransport',
  484. // 'host' => $host,
  485. // 'username' => $smtp_username,
  486. // 'password' => $password,
  487. // 'port' => $port,
  488. // 'encryption' => 'ssl',
  489. // ],
  490. // 'messageConfig' => [
  491. // 'charset' => 'UTF-8',
  492. // 'from' => [$pay_mail => 'Noryatai']
  493. // ],
  494. // ]);
  495. // }else{
  496. // // 设置新的邮箱地址发送
  497. // Yii::$app->set('mailer', [
  498. // 'class' => 'yii\swiftmailer\Mailer',
  499. // 'useFileTransport' => false,
  500. // 'transport' => [
  501. // 'class' => 'Swift_SmtpTransport',
  502. // 'host' => $host,
  503. // 'username' => $smtp_username,
  504. // 'password' => $password,
  505. // 'port' => $port,
  506. // 'encryption' => 'ssl',
  507. // ],
  508. // 'messageConfig' => [
  509. // 'charset' => 'UTF-8',
  510. // 'from' => [$smtp_username => 'Noryatai']
  511. // ],
  512. // ]);
  513. // }
  514. //
  515. // }
  516. if($subject=="訂單信息"){
  517. $pay_mail_num = intval($config->pay_mail_num);
  518. if($pay_mail_num == 0){
  519. $smtp_username = "admin@fastpaypro.net";
  520. $host = 'hwsmtppay.exmail.qq.com';
  521. $port = '4650';
  522. // 设置新的邮箱地址发送
  523. Yii::$app->set('mailer', [
  524. 'class' => 'yii\swiftmailer\Mailer',
  525. 'useFileTransport' => false,
  526. 'transport' => [
  527. 'class' => 'Swift_SmtpTransport',
  528. 'host' => $host,
  529. 'username' => $smtp_username,
  530. 'password' => 'Fastpak99',
  531. 'port' => $port,
  532. 'encryption' => 'ssl',
  533. ],
  534. 'messageConfig' => [
  535. 'charset' => 'UTF-8',
  536. 'from' => [$smtp_username => 'fastpaypro']
  537. ],
  538. ]);
  539. }else{
  540. $pay_mail = $config->pay_mail;
  541. $smtp_username = "apikey";
  542. $host = 'smtp.sendgrid.net';
  543. $port = '465';
  544. // 设置新的邮箱地址发送
  545. Yii::$app->set('mailer', [
  546. 'class' => 'yii\swiftmailer\Mailer',
  547. 'useFileTransport' => false,
  548. 'transport' => [
  549. 'class' => 'Swift_SmtpTransport',
  550. 'host' => $host,
  551. 'username' => $smtp_username,
  552. 'password' => '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',
  553. 'port' => $port,
  554. 'encryption' => 'ssl',
  555. ],
  556. 'messageConfig' => [
  557. 'charset' => 'UTF-8',
  558. 'from' => [$pay_mail => $pay_mail]
  559. ],
  560. ]);
  561. }
  562. }
  563. $mail = \Yii::$app->mailer->compose();
  564. $mail->setTo($to);
  565. $mail->setSubject($subject);
  566. $mail->setHtmlBody( '<html>'.$body);
  567. $result = $mail->send();
  568. if ($result) {
  569. MailRecord::updateAll(['status' => 1], "id={$mid}" );
  570. return true;
  571. }else{
  572. self::sendButNotSaveRecord($subject, $to, $from, $body, $mid);
  573. Yii::warning('邮件发送失败'.VarDumper::dumpAsString($result),__METHOD__);
  574. }
  575. }
  576. }