86 lines
2.6 KiB
PHP
86 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace WizdomNetworks\WizeWeb\Utils;
|
|
|
|
use PHPMailer\PHPMailer\PHPMailer;
|
|
use PHPMailer\PHPMailer\Exception;
|
|
|
|
/**
|
|
* 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()
|
|
{
|
|
$this->mailer = new PHPMailer(true);
|
|
$this->configure();
|
|
}
|
|
|
|
/**
|
|
* 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
|
|
{
|
|
$this->mailer->isSMTP();
|
|
$this->mailer->Host = getenv('MAIL_HOST');
|
|
$this->mailer->SMTPAuth = true;
|
|
$this->mailer->Username = getenv('MAIL_USER');
|
|
$this->mailer->Password = getenv('MAIL_PASSWORD');
|
|
$this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
|
|
$this->mailer->Port = (int) getenv('MAIL_PORT');
|
|
$this->mailer->setFrom(getenv('MAIL_FROM_EMAIL'), getenv('MAIL_FROM_NAME'));
|
|
Logger::info('Mailer configured successfully.');
|
|
}
|
|
|
|
/**
|
|
* 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->addAddress($to);
|
|
$this->mailer->Subject = $subject;
|
|
$this->mailer->Body = $body;
|
|
$this->mailer->AltBody = $altBody;
|
|
|
|
if ($this->mailer->send()) {
|
|
Logger::info("Email sent successfully to $to with subject: $subject.");
|
|
return true;
|
|
} else {
|
|
Logger::error("Failed to send email to $to with subject: $subject.");
|
|
return false;
|
|
}
|
|
} catch (Exception $e) {
|
|
Logger::error("Mailer error while sending email to $to: " . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
}
|