<?php declare(strict_types=1);$root=dirname(__DIR__);$config=require $root.'/config.php';$emailFile=$root.'/config/email.php';if(!is_file($emailFile)){fwrite(STDERR,"Copy config/email.example.php to config/email.php\n");exit(1);}$mailcfg=require $emailFile;if(!$mailcfg['enabled'])exit("Email disabled\n");$autoload=$root.'/vendor/autoload.php';if(!is_file($autoload)){fwrite(STDERR,"Run composer install\n");exit(1);}require $autoload;$pdo=new PDO('sqlite:'.$config['database_path'],null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);$rows=$pdo->query("SELECT * FROM email_queue WHERE queue_status IN('pending','failed') AND attempts<5 AND (next_attempt_at IS NULL OR next_attempt_at<=datetime('now')) ORDER BY id LIMIT 20")->fetchAll();foreach($rows as $x){try{$pdo->prepare("UPDATE email_queue SET queue_status='sending',attempts=attempts+1,last_attempt_at=datetime('now') WHERE id=?")->execute([$x['id']]);$m=new PHPMailer\PHPMailer\PHPMailer(true);$m->isSMTP();$m->Host=$mailcfg['host'];$m->Port=$mailcfg['port'];$m->SMTPAuth=true;$m->Username=$mailcfg['username'];$m->Password=$mailcfg['password'];$m->SMTPSecure=$mailcfg['encryption'];$m->setFrom($mailcfg['from_email'],$mailcfg['from_name']);$m->addAddress($x['recipient_email']);$m->Subject=$x['subject'];$m->Body=$x['body_text'];$m->send();$pdo->prepare("UPDATE email_queue SET queue_status='sent',sent_at=datetime('now'),last_error=NULL WHERE id=?")->execute([$x['id']]);}catch(Throwable $e){$pdo->prepare("UPDATE email_queue SET queue_status='failed',next_attempt_at=datetime('now','+15 minutes'),last_error=? WHERE id=?")->execute([substr($e->getMessage(),0,1000),$x['id']]);}}echo count($rows)." messages processed\n";