WizdomWeb/app/Utils/Mailer.php

98 lines
3.1 KiB
PHP

<?php
namespace WizdomNetworks\WizeWeb\Utils;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use WizdomNetworks\WizeWeb\Utils\Logger;
use WizdomNetworks\WizeWeb\Utils\ErrorHandler;
/**
* Mailer Utility
*
* A utility class for sending emails using PHPMailer.
*
* Integrates logging for email success and failure events.
*/
class Mailer
{
/**
* @var PHPMailer The PHPMailer instance used for sending emails.
*/
protected PHPMailer $mailer;
/**
* Mailer constructor.
*
* Initializes the PHPMailer instance and configures it based on environment variables.
*
* @throws Exception If PHPMailer configuration fails.
*/
public function __construct()
{
try {
$this->mailer = new PHPMailer(true);
$this->configure();
} catch (Exception $e) {
Logger::error('Failed to initialize Mailer: ' . $e->getMessage());
ErrorHandler::exception($e);
throw $e;
}
}
/**
* Configures the PHPMailer instance.
*
* Reads email configuration from environment variables such as MAIL_HOST, MAIL_USER, MAIL_PASSWORD, etc.
*
* @throws Exception If any configuration errors occur.
*/
protected function configure(): void
{
try {
$this->mailer->isSMTP();
$this->mailer->Host = $_ENV['MAIL_HOST'];
$this->mailer->SMTPAuth = true;
$this->mailer->Username = $_ENV['MAIL_USER'];
$this->mailer->Password = $_ENV['MAIL_PASSWORD'];
$this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$this->mailer->Port = (int) $_ENV['MAIL_PORT'];
$this->mailer->setFrom($_ENV['MAIL_FROM_EMAIL'], $_ENV['MAIL_FROM_NAME']);
Logger::info('Mailer configured successfully.');
} catch (Exception $e) {
Logger::error('Mailer configuration failed: ' . $e->getMessage());
ErrorHandler::exception($e);
throw $e;
}
}
/**
* Sends an email.
*
* @param string $to The recipient's email address.
* @param string $subject The email subject.
* @param string $body The HTML content of the email.
* @param string $altBody The plain-text alternative content of the email (optional).
*
* @return bool True if the email was sent successfully, false otherwise.
*/
public function send(string $to, string $subject, string $body, string $altBody = ''): bool
{
try {
$this->mailer->clearAddresses();
$this->mailer->addAddress($to);
$this->mailer->Subject = $subject;
$this->mailer->Body = $body;
$this->mailer->AltBody = $altBody;
$this->mailer->send();
Logger::info("Email sent successfully to $to with subject: $subject.");
return true;
} catch (Exception $e) {
Logger::error("Failed to send email to $to: " . $e->getMessage());
ErrorHandler::exception($e);
return false;
}
}
}