EmailLib.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Support\Facades\Mail;
  4. use Illuminate\Support\Facades\View;
  5. use Illuminate\Mail\Mailables\Address;
  6. use App\Mail\EmailForQueuing;
  7. use Exception;
  8. class EmailLib
  9. {
  10. public string $host;
  11. public int $port;
  12. public string $user;
  13. public string $pw;
  14. public string $from; // 발송자
  15. public string $name;
  16. public array $data;
  17. public array $error;
  18. public array $history; // 이메일 전송 내역 정보
  19. public array $result; // 이메일 전송 결과 정보
  20. public int $total; // 전송 횟수
  21. public int $success; // 성공 횟수
  22. public int $failed; // 실패 횟수
  23. public array $message; // 처리 결과
  24. public array $mails; // 대상 이메일
  25. public function __construct()
  26. {
  27. $this->host = env('MAIL_HOST');
  28. $this->port = env('MAIL_PORT');
  29. $this->user = env('MAIL_USERNAME');
  30. $this->pw = env('MAIL_PASSWORD');
  31. $this->from = env('MAIL_FROM_ADDRESS');
  32. $this->name = env('MAIL_FROM_NAME');
  33. $this->_init();
  34. }
  35. /**
  36. * 초기화
  37. */
  38. private function _init(): void
  39. {
  40. $this->data = [];
  41. $this->error = [];
  42. $this->history = [];
  43. $this->result = [];
  44. $this->total = 0;
  45. $this->success = 0;
  46. $this->failed = 0;
  47. $this->message = [];
  48. $this->mails = [];
  49. }
  50. /**
  51. * 테스트 전송
  52. */
  53. public function test(array $params): void
  54. {
  55. $subject = 'This is Test Email';
  56. Mail::send('admin.config.test.form', $params, function ($message) use ($params, $subject) {
  57. $message->from($this->from, $this->name);
  58. $message->to($params['email'], $params['name'])->subject($subject);
  59. });
  60. }
  61. /**
  62. * 오류 조회
  63. */
  64. public function errors(): array
  65. {
  66. return array_filter($this->error);
  67. }
  68. /**
  69. * 전송 데이터 설정
  70. */
  71. private function _add($users): bool
  72. {
  73. $set = function ($user) {
  74. $this->mails[] = $user;
  75. };
  76. if (is_array($users)) {
  77. foreach ($users as $user) {
  78. if (!filter_var($user->email, FILTER_VALIDATE_EMAIL)) {
  79. $this->error[] = "{$user->email} 는 잘못된 이메일 형식입니다.";
  80. return false;
  81. }
  82. $set($user);
  83. }
  84. } else {
  85. $set(current($users));
  86. }
  87. return true;
  88. }
  89. /**
  90. * 이메일 발송
  91. */
  92. private function _push(string $sendMailFormType): bool
  93. {
  94. try {
  95. if (count($this->mails) > 0) {
  96. $configs = $this->_replace();
  97. foreach ($this->mails as $user) {
  98. // 발송 양식
  99. $title = config($sendMailFormType . '_title');
  100. $content = config($sendMailFormType . '_content');
  101. $mapping = array_merge($configs, [
  102. '{회원아이디}' => $user->id,
  103. '{회원실명}' => $user->name,
  104. '{회원이름}' => $user->name,
  105. '{회원닉네임}' => $user->nickname,
  106. '{회원이메일}' => $user->email,
  107. '{메일수신여부}' => ($user->receive_email ? '동의' : '거부'),
  108. '{문자수신여부}' => ($user->receive_sms ? '동의' : '거부'),
  109. '{쪽지수신여부}' => ($user->receive_note ? '동의' : '거부'),
  110. '{최종로그인시간}' => $user->last_login_at->format('Y년 m월 d일 H시i분'),
  111. '{휴면전환예정일}' => $user->last_login_at->addYear(1)->format('Y년 m월 d일')
  112. ]);
  113. $html = View::make('component.form.email', ['content' => $content])->render();
  114. // 치환 변수 처리
  115. foreach ($mapping as $k => $v) {
  116. $title = str_replace($k, $v, $title);
  117. $html = str_replace($k, $v, $html);
  118. }
  119. Mail::send(new EmailForQueuing(
  120. new Address($this->from, $this->name),
  121. new Address($user->email, $user->name),
  122. $title,
  123. $html
  124. ));
  125. $this->total++;
  126. }
  127. }
  128. $this->success++;
  129. return true;
  130. } catch (Exception $e) {
  131. $this->error[] = $e->getMessage();
  132. $this->failed++;
  133. return false;
  134. }
  135. }
  136. /**
  137. * 치환 대상 변수
  138. */
  139. private function _replace($config = new Config()): array
  140. {
  141. return [
  142. '{홈페이지명}' => $config->item('site_title'),
  143. '{홈페이지주소}' => $config->item('company_site_url'),
  144. '{회원아이디}' => null,
  145. '{회원실명}' => null,
  146. '{회원닉네임}' => null,
  147. '{회원이메일}' => null,
  148. '{메일인증주소}' => null,
  149. '{메일수신여부}' => null,
  150. '{문자수신여부}' => null,
  151. '{쪽지수신여부}' => null,
  152. '{최종로그인시간}' => null,
  153. '{회원아이피}' => $config->item('site_title'),
  154. '{회사명}' => $config->item('company_name'),
  155. '{사업자등록번호}' => $config->item('company_reg_no'),
  156. '{대표자명}' => $config->item('company_owner'),
  157. '{대표전화번호}' => $config->item('company_phone'),
  158. '{FAX번호}' => $config->item('company_fax'),
  159. '{통신판매업신고번호}' => $config->item('company_retail_sale_no'),
  160. '{부가통신사업자번호}' => $config->item('company_added_sale_no'),
  161. '{사업장우편번호}' => $config->item('company_zip_code'),
  162. '{사업장주소}' => $config->item('company_address'),
  163. '{호스팅서비스}' => $config->item('company_hosting'),
  164. '{정보관리책임자명}' => $config->item('company_admin_name'),
  165. '{정보관리책임자이메일}' => $config->item('company_admin_email'),
  166. '{입금은행}' => $config->item('company_bank_name'),
  167. '{입금계좌}' => $config->item('company_bank_number'),
  168. '{휴면전환예정일}' => null
  169. ];
  170. }
  171. /**
  172. * 이메일 전송
  173. */
  174. public function send(string $sendMailFormType, User|UserDormant ...$user): bool
  175. {
  176. try{
  177. if(!$this->_add($user)) {
  178. throw new Exception();
  179. }
  180. if(!$this->_push($sendMailFormType)) {
  181. throw new Exception();
  182. }
  183. return true;
  184. }catch(Exception) {
  185. return false;
  186. }
  187. }
  188. }