Files
webgis/poverty-mapping/src/api/auth/mail_helper.php
T

112 lines
3.3 KiB
PHP

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once __DIR__ . '/../../../vendor/autoload.php';
// Load .env file
$dotenvPath = __DIR__ . '/../../../';
if(file_exists($dotenvPath . '.env')){
try{
$dotenv = Dotenv\Dotenv::createUnsafeMutable($dotenvPath);
$dotenv->safeLoad();
}catch(Exception $e){}
}
function env($k, $default = null){
$val = $_ENV[$k] ?? null;
if($val === null || $val === ''){ $val = getenv($k); }
return ($val !== false && $val !== '') ? $val : $default;
}
function send_mail_phpmailer($to, $subject, $body, $isHtml = false){
try{
$mail = new PHPMailer(true);
$smtpHost = env('SMTP_HOST');
$smtpPort = env('SMTP_PORT', '587');
$smtpUser = env('SMTP_USER');
$smtpPass = env('SMTP_PASS');
$smtpEnc = env('SMTP_ENCRYPTION', 'tls');
$from = env('MAIL_FROM', 'no-reply@localhost');
$fromName = env('MAIL_FROM_NAME', 'WebGIS');
if($smtpHost){
$mail->isSMTP();
$mail->Host = gethostbyname($smtpHost); // Force IPv4
$mail->SMTPAuth = true;
$mail->Username = $smtpUser;
$mail->Password = $smtpPass;
$mail->Port = intval($smtpPort);
// Bypass SSL verification issues with IP hostname in Docker
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if(strtolower($smtpEnc) === 'ssl'){
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
} elseif(strtolower($smtpEnc) === 'tls'){
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
} else {
$mail->SMTPSecure = false;
$mail->SMTPAutoTLS = false;
}
}
$mail->setFrom($from, $fromName);
$mail->addAddress($to);
$mail->Subject = $subject;
if($isHtml){
$mail->isHTML(true);
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
} else {
$mail->Body = $body;
}
$mail->send();
return true;
}catch(Exception $e){
error_log('PHPMailer Error: ' . $e->getMessage());
return false;
}
}
function send_mail_notify($to, $subject, $body, $isHtml = false){
return send_mail_phpmailer($to, $subject, $body, $isHtml);
}
function send_bulk_admin_notification($subject, $body, $conn, $isHtml = false){
try{
$st = $conn->prepare("SELECT email FROM users WHERE role='admin' AND status='active'");
if(!$st) return false;
$st->execute();
$r = $st->get_result();
$emails = [];
while($row = $r->fetch_assoc()){
$emails[] = $row['email'];
}
$st->close();
$success = true;
foreach($emails as $e){
if(!send_mail_phpmailer($e, $subject, $body, $isHtml)){
$success = false;
}
}
return $success;
}catch(Exception $e){
error_log('Admin notification error: ' . $e->getMessage());
return false;
}
}
?>