Files
casadoc/public/userportal/api/_mail.php
T
2026-07-27 21:04:07 +03:00

70 lines
2.2 KiB
PHP

<?php
// SMTP delivery via PHPMailer (already a project dependency).
require_once __DIR__ . '/../../../vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
/** Treats the literal "null" from .env as "not set". */
function mail_env(string $key): string
{
$value = (string) (getenv($key) ?: '');
return ($value === 'null') ? '' : $value;
}
/** Never surfaces the SMTP error to the caller: it can leak host and credentials. */
function send_mail(string $to, string $subject, string $html): bool
{
if (!class_exists(PHPMailer::class)) {
error_log('mail failed: PHPMailer not installed');
return false;
}
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = mail_env('MAIL_HOST') ?: 'localhost';
$mail->Port = (int) (mail_env('MAIL_PORT') ?: 587);
$mail->CharSet = 'UTF-8';
// Default is 300s: an unreachable SMTP would otherwise stall registration.
$mail->Timeout = 10;
if ($user = mail_env('MAIL_USERNAME')) {
$mail->SMTPAuth = true;
$mail->Username = $user;
$mail->Password = mail_env('MAIL_PASSWORD');
}
if ($enc = mail_env('MAIL_ENCRYPTION')) {
$mail->SMTPSecure = $enc;
}
$mail->setFrom(
mail_env('MAIL_FROM_ADDRESS') ?: 'noreply@casadoc.app',
mail_env('MAIL_FROM_NAME') ?: 'CasaDoc'
);
$mail->addAddress($to);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $html;
return $mail->send();
} catch (Throwable $e) {
error_log('mail failed: ' . $e->getMessage());
return false;
}
}
function send_code_mail(string $to, string $code, bool $isReset = false): bool
{
$subject = $isReset ? 'CasaDoc password reset code' : 'CasaDoc verification code';
$intro = $isReset
? 'Use this code to reset your CasaDoc password:'
: 'Use this code to confirm your e-mail address:';
$html = '<p>' . $intro . '</p>'
. '<p style="font-size:28px;font-weight:bold;letter-spacing:4px">' . htmlspecialchars($code) . '</p>'
. '<p>The code expires in 15 minutes. If you did not request it, ignore this e-mail.</p>';
return send_mail($to, $subject, $html);
}