Mail.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. <?php
  2. /**
  3. * 邮件
  4. *
  5. * @author mybsdc <[email protected]>
  6. * @date 2019/5/12
  7. * @time 16:38
  8. */
  9. namespace Luolongfei\Libs\MessageServices;
  10. use Luolongfei\App\Exceptions\LlfException;
  11. use Luolongfei\Libs\Log;
  12. use PHPMailer\PHPMailer\PHPMailer;
  13. use PHPMailer\PHPMailer\Exception as MailException;
  14. use Luolongfei\Libs\Connector\MessageGateway;
  15. class Mail extends MessageGateway
  16. {
  17. /**
  18. * @var PHPMailer
  19. */
  20. private $phpMailerInstance;
  21. /**
  22. * @throws MailException
  23. */
  24. public function __construct()
  25. {
  26. $this->phpMailerInstance = new PHPMailer(true);
  27. $this->init();
  28. }
  29. /**
  30. * 初始化邮箱配置
  31. *
  32. * @throws MailException
  33. */
  34. protected function init()
  35. {
  36. $username = config('message.mail.username');
  37. $password = config('message.mail.password');
  38. list($host, $secure, $port) = $this->getBasicMailConf($username);
  39. $this->phpMailerInstance->SMTPDebug = config('debug') ? 2 : 0; // Debug 0:关闭 1:客户端信息 2:客户端和服务端信息
  40. $this->phpMailerInstance->isSMTP(); // 告诉 PHPMailer 使用 SMTP
  41. $this->phpMailerInstance->Host = $host; // SMTP 服务器
  42. $this->phpMailerInstance->SMTPAuth = true; // 启用 SMTP 身份验证
  43. $this->phpMailerInstance->Username = $username; // 账号
  44. $this->phpMailerInstance->Password = $password; // 密码或授权码
  45. $this->phpMailerInstance->SMTPSecure = $secure; // 将加密系统设置为使用 - ssl(不建议使用)或 tls
  46. $this->phpMailerInstance->Port = $port; // 设置 SMTP 端口号 - tsl 使用 587 端口,ssl 使用 465 端口
  47. $this->phpMailerInstance->CharSet = 'UTF-8'; // 防止中文邮件乱码
  48. $this->phpMailerInstance->setLanguage('zh_cn', VENDOR_PATH . '/phpmailer/phpmailer/language/'); // 设置语言
  49. $this->phpMailerInstance->setFrom($username, 'Im robot'); // 发件人
  50. }
  51. /**
  52. * 获取邮箱基本配置
  53. *
  54. * @param string $username
  55. *
  56. * @return array
  57. * @throws MailException
  58. */
  59. public function getBasicMailConf(string $username)
  60. {
  61. if (stripos($username, '@gmail.com') !== false) {
  62. $host = 'smtp.gmail.com';
  63. $secure = 'tls';
  64. $port = 587;
  65. } else if (stripos($username, '@qq.com') !== false) {
  66. $host = 'smtp.qq.com';
  67. $secure = 'tls';
  68. $port = 587;
  69. } else if (stripos($username, '@163.com') !== false) {
  70. $host = 'smtp.163.com';
  71. $secure = 'ssl';
  72. $port = 465;
  73. } else if (stripos($username, '@vip.163.com') !== false) {
  74. $host = 'smtp.vip.163.com';
  75. $secure = 'ssl';
  76. $port = 465;
  77. } else if (stripos($username, '@outlook.com') !== false) {
  78. $host = 'smtp.office365.com';
  79. $secure = 'starttls';
  80. $port = 587;
  81. } else {
  82. $host = config('message.mail.host');
  83. $secure = config('message.mail.encryption');
  84. $port = (int)config('message.mail.port');
  85. if (!($host && $secure && $port)) {
  86. throw new MailException('目前支持Gmail、QQ邮箱、163邮箱以及Outlook邮箱自动识别配置,其它类型的邮箱或者自建邮箱,'
  87. . '请在 .env 文件中追加“自定义邮箱配置”的所有相关项,否则无法使用邮件服务。');
  88. }
  89. }
  90. return [$host, $secure, $port];
  91. }
  92. /**
  93. * 生成域名 html
  94. *
  95. * @param array $domains
  96. *
  97. * @return string
  98. */
  99. public function genDomainsHtml(array $domains)
  100. {
  101. $domainsHtml = '';
  102. foreach ($domains as $domain) {
  103. $domainsHtml .= sprintf('<a href="http://%s" rel="noopener" target="_blank">%s</a>', $domain, $domain);
  104. }
  105. return $domainsHtml;
  106. }
  107. /**
  108. * 生成域名状态 html
  109. *
  110. * @param array $domainStatus
  111. *
  112. * @return string
  113. */
  114. public function genDomainStatusHtml(array $domainStatus)
  115. {
  116. $domainStatusHtml = '';
  117. foreach ($domainStatus as $domain => $daysLeft) {
  118. $domainStatusHtml .= sprintf('<a href="http://%s" rel="noopener" target="_blank">%s</a>还有 <span style="font-weight: bold; font-size: 16px;">%d</span> 天到期,', $domain, $domain, $daysLeft);
  119. }
  120. $domainStatusHtml = rtrim($domainStatusHtml, ',') . "。";
  121. return $domainStatusHtml;
  122. }
  123. /**
  124. * 送信
  125. *
  126. * @param string $content
  127. * @param string $subject
  128. * @param integer $type
  129. * @param array $data
  130. * @param string|null $recipient
  131. * @param mixed ...$params
  132. *
  133. * @return bool
  134. * @throws LlfException
  135. * @throws MailException
  136. */
  137. public function send(string $content, string $subject = '', int $type = 1, array $data = [], ?string $recipient = null, ...$params)
  138. {
  139. $recipient = $recipient ?: config('message.mail.to');
  140. if (!$recipient) {
  141. throw new LlfException(34520012);
  142. }
  143. if ($content === '' && empty($data)) {
  144. throw new \Exception(lang('error_msg.100002'));
  145. }
  146. if ($content !== '' && $data) {
  147. throw new \Exception(lang('error_msg.100004'));
  148. }
  149. $this->phpMailerInstance->addAddress($recipient, config('message.mail.recipient_name', '主人')); // 添加收件人,参数2选填
  150. $this->phpMailerInstance->addReplyTo(config('message.mail.reply_to', '[email protected]'), config('message.mail.reply_to_name', '作者')); // 备用回复地址,收到的回复的邮件将被发到此地址
  151. /**
  152. * 抄送和密送都是添加收件人,抄送方式下,被抄送者知道除被密送者外的所有的收件人,密送方式下,
  153. * 被密送者知道所有的被抄送者,但不知道其它的被密送者。
  154. * 抄送好比@,密送好比私信。
  155. */
  156. // $this->phpMailerInstance->addCC('[email protected]'); // 抄送
  157. // $this->phpMailerInstance->addBCC('[email protected]'); // 密送
  158. // 添加附件,参数2选填
  159. // $this->phpMailerInstance->addAttachment('README.md', '说明.txt');
  160. // 标题
  161. $subject = $subject === '' ? mb_substr($content, 0, 12) . '...' : $subject;
  162. $this->phpMailerInstance->Subject = $subject;
  163. /**
  164. * 正文
  165. * 使用 html 文件内容作为正文,其中的图片将被 base64 编码,另确保 html 样式为内联形式,且某些样式可能需要 !important 方能正常显示,
  166. * msgHTML 方法的第二个参数指定 html 内容中图片的路径,在转换时会拼接 html 中图片的相对路径得到完整的路径,最右侧无需“/”,PHPMailer
  167. * 源码里有加。 css 中的背景图片不会被转换,这是 PHPMailer 已知问题,建议外链
  168. * 此处也可替换为:
  169. * $this->phpMailerInstance->isHTML(true); // 设为html格式
  170. * $this->phpMailerInstance->Body = '正文'; // 支持html
  171. * $this->phpMailerInstance->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'; // 纯文本消息正文。不支持html预览的邮件客户端将显示此预览消息,其它情况将显示正常的body
  172. */
  173. if ($type === 1) {
  174. $template = file_get_contents(RESOURCES_PATH . '/mail/notice.html');
  175. $message = sprintf($template, $content);
  176. } else if ($type === 2) {
  177. $template = file_get_contents(RESOURCES_PATH . '/mail/successful_renewal.html');
  178. $realData = [
  179. $data['username'],
  180. $data['renewalSuccessArr'] ? sprintf('续期成功:%s<br>', $this->genDomainsHtml($data['renewalSuccessArr'])) : '',
  181. $data['renewalFailuresArr'] ? sprintf('续期出错:%s<br>', $this->genDomainsHtml($data['renewalFailuresArr'])) : '',
  182. $this->genDomainStatusHtml($data['domainStatusArr'])
  183. ];
  184. $message = $this->genMessageContent($realData, $template);
  185. } else if ($type === 3) {
  186. $template = file_get_contents(RESOURCES_PATH . '/mail/no_renewal_required.html');
  187. $realData = [
  188. $data['username'],
  189. $this->genDomainStatusHtml($data['domainStatusArr'])
  190. ];
  191. $message = $this->genMessageContent($realData, $template);
  192. } else {
  193. throw new \Exception(lang('error_msg.100003'));
  194. }
  195. $this->phpMailerInstance->msgHTML($message, APP_PATH . '/mail');
  196. try {
  197. if (!$this->phpMailerInstance->send()) {
  198. throw new MailException($this->phpMailerInstance->ErrorInfo);
  199. }
  200. return true;
  201. } catch (\Exception $e) {
  202. system_log('邮件发送失败:' . $e->getMessage());
  203. return false;
  204. }
  205. }
  206. }