| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?php
- namespace cx_newsletter;
- use \Exception;
- use \wp_mail;
- class mail_manager
- extends use_settings {
- public function prepare(single_mail $target) : void {
- if ($target->reply_to === null) {
- $target->reply_to = $this->get_settings()->get('reply_to_address');
- }
-
- if (!$target->is_good()) {
- throw new Exception($target->validate());
- }
- $this->target = $target;
- }
- public function send(bool $debug = false) : bool {
- if ($this->target === null) {
- return false;
- }
- if (!$this->get_settings()->use_custom_smtp()) {
- return $this->send_by_wp_mail();
- }
-
- if ($debug) {
- $this->send_by_phpmailer();
- return true;
- }
-
- try {
- $this->send_by_phpmailer($debug);
- } catch (Exception $exception) {
- return false;
- }
-
- return true;
- }
- private function send_by_phpmailer(bool $debug = false) : void {
- if (!class_exists('\PHPMailer\PHPMailer\PHPMailer')) {
- use_php_mailer();
- }
- $mailer = new \PHPMailer\PHPMailer\PHPMailer(true);
- if ($debug) {
- $mailer->SMTPDebug = \PHPMailer\PHPMailer\SMTP::DEBUG_SERVER;
- } else {
- $mailer->SMTPDebug = \PHPMailer\PHPMailer\SMTP::DEBUG_OFF;
- }
- $mailer->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
- $mailer->isSMTP();
- $mailer->Host = $this->get_settings()->get('smtp_address');
- $mailer->Port = intval($this->get_settings()->get('smtp_port'));
- $mailer->SMTPAuth = true;
- $mailer->Username = $this->get_settings()->get('smtp_user');
- $mailer->Password = $this->get_settings()->get('smtp_password');
- $mailer->addAddress($this->target->to);
- $mailer->addReplyTo($this->target->reply_to);
- $mailer->setFrom($this->get_settings()->get('source_address'));
- $mailer->Subject = $this->target->title;
- $mailer->Body = $this->target->content;
- if ($this->target->is_html) {
- $mailer->AltBody = strip_tags($this->target->content);
- } else {
- $mailer->AltBody = $this->target->content;
- }
- $mailer->send();
- }
- private function send_by_wp_mail() : bool{
- $headers = $this->target->headers;
- $headers['From'] = $this->get_settings()->get('source_address');
- $headers['Reply-To'] = $this->target->reply_to;
- if ($this->target->is_html) {
- $headers['Content-Type'] = 'text/html';
- } else {
- $headers['Content-Type'] = 'text/plain';
- }
- return wp_mail(
- $this->target->to,
- $this->target->title,
- $this->target->content,
- $headers
- );
- }
- private ?single_mail $target = null;
- }
|