MailHelper.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]); //获取当前邮箱的配置项
  209. if($config->mail_number){
  210. $number = intval($config->mail_number);
  211. switch ($number){
  212. case 1:
  213. $smtp_username = "admin@fusian-fx.com";
  214. $host = 'hwsmtp.exmail.qq.com';
  215. $port = '465';
  216. break;
  217. case 2:
  218. $smtp_username = "admin@fusian-fx-mail1.com";
  219. $host = 'hwsmtp1.exmail.qq.com';
  220. $port = '4650';
  221. break;
  222. case 3:
  223. $smtp_username = "admin@fusian-fx-mail2.com";
  224. $host = 'hwsmtp2.exmail.qq.com';
  225. $port = '4650';
  226. break;
  227. case 4:
  228. $smtp_username = "admin@fusian-fx-mail3.com";
  229. $host = 'hwsmtp3.exmail.qq.com';
  230. $port = '4650';
  231. break;
  232. case 5:
  233. $smtp_username = "admin@fusian-fx-mail4.com";
  234. $host = 'hwsmtp4.exmail.qq.com';
  235. $port = '4650';
  236. break;
  237. default:
  238. $smtp_username = "admin@fusian-fx.com";
  239. $host = 'hwsmtp.exmail.qq.com';
  240. $port = '465';
  241. }
  242. // 设置新的邮箱地址发送
  243. Yii::$app->set('mailer', [
  244. 'class' => 'yii\swiftmailer\Mailer',
  245. 'useFileTransport' => false,
  246. 'transport' => [
  247. 'class' => 'Swift_SmtpTransport',
  248. 'host' => $host,
  249. 'username' => $smtp_username,
  250. 'password' => 'Fusiak99',
  251. 'port' => $port,
  252. 'encryption' => 'ssl',
  253. ],
  254. 'messageConfig' => [
  255. 'charset' => 'UTF-8',
  256. 'from' => [$smtp_username => 'Fusian']
  257. ],
  258. ]);
  259. }
  260. $mail = \Yii::$app->mailer->compose();
  261. $mail->setTo($to);
  262. $mail->setSubject($subject);
  263. $mail->setHtmlBody( '<html>'.$replace_content);
  264. $result = $mail->send();
  265. if ($result) {
  266. $isSuccess = true;
  267. } else {
  268. Yii::warning('邮件发送失败' . VarDumper::dumpAsString($result), __METHOD__);
  269. }
  270. $status = ($isSuccess) ? 1 : 2;
  271. MailRecord::updateAll(['status' => $status], "id={$mailid}" );
  272. return $isSuccess;
  273. }
  274. /**
  275. * 将模板中的变量替换为入参
  276. * @param $content string
  277. * @param $paramArray array
  278. * @return string
  279. */
  280. public static function replaceVariable($content, $paramArray)
  281. {
  282. if (!empty($content) && !empty($paramArray)) {
  283. foreach ($paramArray as $key => $value) {
  284. $variable='${'.$key.'}';
  285. $variable1 = '#{'.$key.'}';
  286. $variable2 = '#'.$key.'#';
  287. if (is_null($value)) {
  288. continue;
  289. }
  290. while (strpos($content, $variable, 0) > -1) {
  291. $content = str_replace($variable, $value, $content);
  292. }
  293. while (strpos($content, $variable1, 0) > -1) {
  294. $content = str_replace($variable1, $value, $content);
  295. }
  296. while (strpos($content, $variable2, 0) > -1) {
  297. $content = str_replace($variable2, $value, $content);
  298. }
  299. }
  300. }
  301. return $content;
  302. }
  303. /**
  304. * 保存发送的邮件记录到crm_mail_record表
  305. * @param $status
  306. * @param $receiver
  307. * @param $subject
  308. * @param $content
  309. * @return bool
  310. */
  311. private static function saveRecord($status, $receiver, $subject, $content)
  312. {
  313. $mailRecord = new MailRecord();
  314. $mailRecord->content = $content;
  315. $mailRecord->receiver = $receiver;
  316. if ($status) {
  317. $mailRecord->status = 1;
  318. } else {
  319. $mailRecord->status = 0;
  320. }
  321. $mailRecord->subject = $subject;
  322. $mailRecord->in_time = DateTimeHelper::microtime_float();
  323. $mailRecord->save();
  324. return $mailRecord->id;
  325. }
  326. /**
  327. * 发送email邮件
  328. * @param $subject
  329. * @param $to
  330. * @param $from
  331. * @param $body
  332. * @param $mid
  333. * @return bool
  334. */
  335. public static function sendButNotSaveRecord($subject, $to, $from, $body, $mid)
  336. {
  337. $isSuccess = false;
  338. $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
  339. /*
  340. $smtp_username = $config->smtp_username;
  341. $smtp_password = $config->smtp_password;
  342. \Yii::$app->mail->apiUser = $smtp_username;
  343. \Yii::$app->mail->apiKey = $smtp_password;
  344. $result = \Yii::$app->mail->sendNormalMail($subject, '<html>'.$body, $to, $from);
  345. if ($result['result'] === true) {
  346. $isSuccess = true;
  347. }
  348. return $isSuccess;
  349. */
  350. $mail = \Yii::$app->mailer->compose();
  351. $mail->setTo($to);
  352. $mail->setSubject($subject);
  353. $mail->setHtmlBody( '<html>'.$body);
  354. if ($mail->send()) {
  355. MailRecord::updateAll(['status' => 1], "id={$mid}" );
  356. return true;
  357. }
  358. return false;
  359. }
  360. }