Mail.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. if (empty($domainStatus)) {
  117. return "无数据。";
  118. }
  119. $domainStatusHtml = '';
  120. foreach ($domainStatus as $domain => $daysLeft) {
  121. $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);
  122. }
  123. $domainStatusHtml = rtrim($domainStatusHtml, ',') . "。";
  124. return $domainStatusHtml;
  125. }
  126. /**
  127. * 送信
  128. *
  129. * @param string $content
  130. * @param string $subject
  131. * @param integer $type
  132. * @param array $data
  133. * @param string|null $recipient
  134. * @param mixed ...$params
  135. *
  136. * @return bool
  137. * @throws LlfException
  138. * @throws MailException
  139. */
  140. public function send(string $content, string $subject = '', int $type = 1, array $data = [], ?string $recipient = null, ...$params)
  141. {
  142. $recipient = $recipient ?: config('message.mail.to');
  143. if (!$recipient) {
  144. throw new LlfException(34520012);
  145. }
  146. $this->check($content, $data);
  147. $this->phpMailerInstance->addAddress($recipient, config('message.mail.recipient_name', '主人')); // 添加收件人,参数2选填
  148. $this->phpMailerInstance->addReplyTo(config('message.mail.reply_to', '[email protected]'), config('message.mail.reply_to_name', '作者')); // 备用回复地址,收到的回复的邮件将被发到此地址
  149. /**
  150. * 抄送和密送都是添加收件人,抄送方式下,被抄送者知道除被密送者外的所有的收件人,密送方式下,
  151. * 被密送者知道所有的被抄送者,但不知道其它的被密送者。
  152. * 抄送好比@,密送好比私信。
  153. */
  154. // $this->phpMailerInstance->addCC('[email protected]'); // 抄送
  155. // $this->phpMailerInstance->addBCC('[email protected]'); // 密送
  156. // 添加附件,参数2选填
  157. // $this->phpMailerInstance->addAttachment('README.md', '说明.txt');
  158. // 标题
  159. $subject = $subject === '' ? mb_substr($content, 0, 12) . '...' : $subject;
  160. $this->phpMailerInstance->Subject = $subject;
  161. /**
  162. * 正文
  163. * 使用 html 文件内容作为正文,其中的图片将被 base64 编码,另确保 html 样式为内联形式,且某些样式可能需要 !important 方能正常显示,
  164. * msgHTML 方法的第二个参数指定 html 内容中图片的路径,在转换时会拼接 html 中图片的相对路径得到完整的路径,最右侧无需“/”,PHPMailer
  165. * 源码里有加。 css 中的背景图片不会被转换,这是 PHPMailer 已知问题,建议外链
  166. * 此处也可替换为:
  167. * $this->phpMailerInstance->isHTML(true); // 设为html格式
  168. * $this->phpMailerInstance->Body = '正文'; // 支持html
  169. * $this->phpMailerInstance->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'; // 纯文本消息正文。不支持html预览的邮件客户端将显示此预览消息,其它情况将显示正常的body
  170. */
  171. if ($type === 1) {
  172. $template = file_get_contents(RESOURCES_PATH . '/mail/notice.html');
  173. $message = sprintf($template, $content);
  174. } else if ($type === 2) {
  175. $template = file_get_contents(RESOURCES_PATH . '/mail/successful_renewal.html');
  176. $realData = [
  177. $data['username'],
  178. $data['renewalSuccessArr'] ? sprintf('续期成功:%s<br>', $this->genDomainsHtml($data['renewalSuccessArr'])) : '',
  179. $data['renewalFailuresArr'] ? sprintf('续期出错:%s<br>', $this->genDomainsHtml($data['renewalFailuresArr'])) : '',
  180. $this->genDomainStatusHtml($data['domainStatusArr'])
  181. ];
  182. $message = $this->genMessageContent($realData, $template);
  183. } else if ($type === 3) {
  184. $template = file_get_contents(RESOURCES_PATH . '/mail/no_renewal_required.html');
  185. $realData = [
  186. $data['username'],
  187. $this->genDomainStatusHtml($data['domainStatusArr'])
  188. ];
  189. $message = $this->genMessageContent($realData, $template);
  190. } else if ($type === 4) {
  191. $template = file_get_contents(RESOURCES_PATH . '/mail/notice.html');
  192. $message = sprintf($template, $this->newLine2Br($content));
  193. } else {
  194. throw new \Exception(lang('error_msg.100003'));
  195. }
  196. $this->phpMailerInstance->msgHTML($message, APP_PATH . '/mail');
  197. try {
  198. if (!$this->phpMailerInstance->send()) {
  199. throw new MailException($this->phpMailerInstance->ErrorInfo);
  200. }
  201. return true;
  202. } catch (\Exception $e) {
  203. system_log('邮件发送失败:' . $e->getMessage());
  204. return false;
  205. }
  206. }
  207. }