'PHPMailer library not found.'];
}
public static function sendMail($to, $subject, $html, $txt, $opts = []) {
return ['error' => 'PHPMailer library not found.'];
}
}
return;
}
}
}
require_once __DIR__ . '/config.php';
class MailService {
private static function createMailer() {
$mail = new PHPMailer(true);
if (MAIL_TRANSPORT === 'smtp') {
$mail->isSMTP();
$mail->Host = SMTP_HOST;
$mail->SMTPAuth = !empty(SMTP_USER);
$mail->Username = SMTP_USER;
$mail->Password = SMTP_PASS;
$mail->SMTPSecure = SMTP_SECURE;
$mail->Port = SMTP_PORT;
} else {
$mail->isSendmail();
}
return $mail;
}
public static function sendMail($to, $subject, $htmlBody, $altBody, $options = []) {
try {
$mail = self::createMailer();
// Recipients
$recipient = $to ?: (getenv('MAIL_TO') ?: MAIL_FROM);
if (is_array($recipient)) {
foreach ($recipient as $r) {
$mail->addAddress($r);
}
} else {
$mail->addAddress($recipient);
}
// From
$fromEmail = $options['from_email'] ?? MAIL_FROM;
$fromName = $options['from_name'] ?? MAIL_FROM_NAME;
$mail->setFrom($fromEmail, $fromName);
// Reply-To
if (isset($options['reply_to'])) {
$mail->addReplyTo($options['reply_to']);
}
// CC/BCC
if (isset($options['cc']) && is_array($options['cc'])) {
foreach ($options['cc'] as $cc) { $mail->addCC($cc); }
}
if (isset($options['bcc']) && is_array($options['bcc'])) {
foreach ($options['bcc'] as $bcc) { $mail->addBCC($bcc); }
}
// Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $htmlBody;
$mail->AltBody = $altBody;
$mail->send();
return ['success' => true];
} catch (Exception $e) {
return ['error' => $mail->ErrorInfo];
}
}
public static function sendContactMessage($name, $email, $message, $to = null, $subject = 'Contact Form Submission') {
$htmlBody = "You have received a new message from your website contact form.
Here are the details:
Name: {$name}
Email: {$email}
Message:
" . nl2br(htmlspecialchars($message));
$altBody = "You have received a new message from your website contact form.\n\nHere are the details:\nName: {$name}\nEmail: {$email}\nMessage:\n" . htmlspecialchars($message);
$options = ['reply_to' => $email];
return self::sendMail($to, $subject, $htmlBody, $altBody, $options);
}
}