13-mail_manager.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace cx_newsletter;
  3. use \Exception;
  4. use \wp_mail;
  5. class mail_manager
  6. extends use_settings {
  7. public function prepare(single_mail $target) : void {
  8. if ($target->reply_to === null) {
  9. $target->reply_to = $this->get_settings()->get('reply_to_address');
  10. }
  11. if (!$target->is_good()) {
  12. throw new Exception($target->validate());
  13. }
  14. $this->target = $target;
  15. }
  16. public function send(bool $debug = false) : bool {
  17. if ($this->target === null) {
  18. return false;
  19. }
  20. if (!$this->get_settings()->use_custom_smtp()) {
  21. return $this->send_by_wp_mail();
  22. }
  23. if ($debug) {
  24. $this->send_by_phpmailer();
  25. return true;
  26. }
  27. try {
  28. $this->send_by_phpmailer($debug);
  29. } catch (Exception $exception) {
  30. return false;
  31. }
  32. return true;
  33. }
  34. private function send_by_phpmailer(bool $debug = false) : void {
  35. if (!class_exists('\PHPMailer\PHPMailer\PHPMailer')) {
  36. use_php_mailer();
  37. }
  38. $mailer = new \PHPMailer\PHPMailer\PHPMailer(true);
  39. if ($debug) {
  40. $mailer->SMTPDebug = \PHPMailer\PHPMailer\SMTP::DEBUG_SERVER;
  41. } else {
  42. $mailer->SMTPDebug = \PHPMailer\PHPMailer\SMTP::DEBUG_OFF;
  43. }
  44. $mailer->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
  45. $mailer->isSMTP();
  46. $mailer->Host = $this->get_settings()->get('smtp_address');
  47. $mailer->Port = intval($this->get_settings()->get('smtp_port'));
  48. $mailer->SMTPAuth = true;
  49. $mailer->Username = $this->get_settings()->get('smtp_user');
  50. $mailer->Password = $this->get_settings()->get('smtp_password');
  51. $mailer->addAddress($this->target->to);
  52. $mailer->addReplyTo($this->target->reply_to);
  53. $mailer->setFrom($this->get_settings()->get('source_address'));
  54. $mailer->Subject = $this->target->title;
  55. $mailer->Body = $this->target->content;
  56. if ($this->target->is_html) {
  57. $mailer->AltBody = strip_tags($this->target->content);
  58. } else {
  59. $mailer->AltBody = $this->target->content;
  60. }
  61. $mailer->send();
  62. }
  63. private function send_by_wp_mail() : bool{
  64. $headers = $this->target->headers;
  65. $headers['From'] = $this->get_settings()->get('source_address');
  66. $headers['Reply-To'] = $this->target->reply_to;
  67. if ($this->target->is_html) {
  68. $headers['Content-Type'] = 'text/html';
  69. } else {
  70. $headers['Content-Type'] = 'text/plain';
  71. }
  72. return wp_mail(
  73. $this->target->to,
  74. $this->target->title,
  75. $this->target->content,
  76. $headers
  77. );
  78. }
  79. private ?single_mail $target = null;
  80. }