251 lines
7.2 KiB
PHP
251 lines
7.2 KiB
PHP
<?php
|
|
/**
|
|
* Mailer - envoi SMTP sans dependance externe.
|
|
*/
|
|
|
|
require_once __DIR__ . '/../config/smtp.php';
|
|
|
|
class Mailer
|
|
{
|
|
private string $host;
|
|
private int $port;
|
|
private string $user;
|
|
private string $pass;
|
|
private string $fromEmail;
|
|
private string $fromName;
|
|
private string $lastMessageId = '';
|
|
|
|
/** @var resource|false */
|
|
private mixed $sock = false;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->host = SMTP_HOST;
|
|
$this->port = SMTP_PORT;
|
|
$this->user = SMTP_USER;
|
|
$this->pass = SMTP_PASS;
|
|
$this->fromEmail = SMTP_FROM_EMAIL;
|
|
$this->fromName = SMTP_FROM_NAME;
|
|
}
|
|
|
|
/**
|
|
* Retourne le Message-ID du dernier email envoye.
|
|
*/
|
|
public function getLastMessageId(): string
|
|
{
|
|
return $this->lastMessageId;
|
|
}
|
|
|
|
/**
|
|
* Envoie un email texte brut.
|
|
*/
|
|
public function send(string $to, string $subject, string $body, string $replyTo = ''): bool
|
|
{
|
|
return $this->dispatch($to, $subject, $body, '', $replyTo);
|
|
}
|
|
|
|
/**
|
|
* Envoie un email HTML avec fallback texte.
|
|
*/
|
|
public function sendHtml(string $to, string $subject, string $htmlBody, string $textBody = '', string $replyTo = ''): bool
|
|
{
|
|
return $this->dispatch($to, $subject, $textBody, $htmlBody, $replyTo);
|
|
}
|
|
|
|
/**
|
|
* Envoi SMTP interne.
|
|
*/
|
|
private function dispatch(string $to, string $subject, string $textBody, string $htmlBody, string $replyTo): bool
|
|
{
|
|
try {
|
|
$to = $this->normalizeEmail($to);
|
|
$replyTo = $replyTo !== '' ? $this->normalizeEmail($replyTo) : '';
|
|
$subject = $this->normalizeHeaderText($subject);
|
|
|
|
$this->connect();
|
|
$this->read(220);
|
|
$this->cmd("EHLO {$this->host}", 250);
|
|
|
|
if ($this->port === 587) {
|
|
$this->cmd('STARTTLS', 220);
|
|
|
|
if (!stream_socket_enable_crypto($this->sock, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
|
|
throw new RuntimeException('STARTTLS negotiation failed');
|
|
}
|
|
|
|
$this->cmd("EHLO {$this->host}", 250);
|
|
}
|
|
|
|
$this->cmd('AUTH LOGIN', 334);
|
|
$this->cmd(base64_encode($this->user), 334);
|
|
$this->cmd(base64_encode($this->pass), 235);
|
|
|
|
$this->cmd("MAIL FROM: <{$this->fromEmail}>", 250);
|
|
$this->cmd("RCPT TO: <{$to}>", [250, 251]);
|
|
$this->cmd('DATA', 354);
|
|
|
|
$this->lastMessageId = '<' . bin2hex(random_bytes(16)) . '@tony-averty.dev>';
|
|
|
|
$msg = 'From: ' . $this->encodeHeader($this->fromName) . " <{$this->fromEmail}>\r\n";
|
|
$msg .= "To: <{$to}>\r\n";
|
|
|
|
if ($replyTo !== '') {
|
|
$msg .= "Reply-To: <{$replyTo}>\r\n";
|
|
}
|
|
|
|
$msg .= 'Subject: ' . $this->encodeHeader($subject) . "\r\n";
|
|
$msg .= "Message-ID: {$this->lastMessageId}\r\n";
|
|
$msg .= "MIME-Version: 1.0\r\n";
|
|
$msg .= "X-Mailer: TonyPortfolio/1.0\r\n";
|
|
|
|
if ($htmlBody !== '') {
|
|
$boundary = 'boundary_' . bin2hex(random_bytes(12));
|
|
$plain = $textBody !== '' ? $textBody : strip_tags($htmlBody);
|
|
|
|
$msg .= "Content-Type: multipart/alternative; boundary=\"{$boundary}\"\r\n\r\n";
|
|
|
|
$msg .= "--{$boundary}\r\n";
|
|
$msg .= "Content-Type: text/plain; charset=UTF-8\r\n";
|
|
$msg .= "Content-Transfer-Encoding: base64\r\n\r\n";
|
|
$msg .= chunk_split(base64_encode($plain)) . "\r\n";
|
|
|
|
$msg .= "--{$boundary}\r\n";
|
|
$msg .= "Content-Type: text/html; charset=UTF-8\r\n";
|
|
$msg .= "Content-Transfer-Encoding: base64\r\n\r\n";
|
|
$msg .= chunk_split(base64_encode($htmlBody)) . "\r\n";
|
|
|
|
$msg .= "--{$boundary}--\r\n";
|
|
} else {
|
|
$msg .= "Content-Type: text/plain; charset=UTF-8\r\n";
|
|
$msg .= "Content-Transfer-Encoding: base64\r\n\r\n";
|
|
$msg .= chunk_split(base64_encode($textBody));
|
|
}
|
|
|
|
$msg .= "\r\n.\r\n";
|
|
|
|
fwrite($this->sock, $msg);
|
|
$this->read(250);
|
|
|
|
$this->cmd('QUIT', 221);
|
|
fclose($this->sock);
|
|
$this->sock = false;
|
|
|
|
return true;
|
|
} catch (Throwable $e) {
|
|
error_log('[Mailer] ' . $e->getMessage());
|
|
|
|
if ($this->sock) {
|
|
@fclose($this->sock);
|
|
$this->sock = false;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Ouvre la connexion SMTP avec verification TLS.
|
|
*/
|
|
private function connect(): void
|
|
{
|
|
$transport = $this->port === 465 ? 'tls' : 'tcp';
|
|
$timeout = 20;
|
|
$context = stream_context_create([
|
|
'ssl' => [
|
|
'verify_peer' => true,
|
|
'verify_peer_name' => true,
|
|
'allow_self_signed' => false,
|
|
'peer_name' => $this->host,
|
|
'SNI_enabled' => true,
|
|
],
|
|
]);
|
|
|
|
$errno = 0;
|
|
$errstr = '';
|
|
|
|
$this->sock = @stream_socket_client(
|
|
"{$transport}://{$this->host}:{$this->port}",
|
|
$errno,
|
|
$errstr,
|
|
$timeout,
|
|
STREAM_CLIENT_CONNECT,
|
|
$context
|
|
);
|
|
|
|
if (!$this->sock) {
|
|
throw new RuntimeException("Connexion SMTP impossible : {$errstr} ({$errno})");
|
|
}
|
|
|
|
stream_set_timeout($this->sock, $timeout);
|
|
}
|
|
|
|
/**
|
|
* Envoie une commande SMTP.
|
|
*/
|
|
private function cmd(string $cmd, int|array $expect = 250): string
|
|
{
|
|
fwrite($this->sock, $cmd . "\r\n");
|
|
return $this->read($expect);
|
|
}
|
|
|
|
/**
|
|
* Lit la reponse SMTP.
|
|
*/
|
|
private function read(int|array $expect): string
|
|
{
|
|
$response = '';
|
|
|
|
while ($line = fgets($this->sock, 1024)) {
|
|
$response .= $line;
|
|
|
|
if (isset($line[3]) && $line[3] === ' ') {
|
|
break;
|
|
}
|
|
}
|
|
|
|
$code = (int) substr($response, 0, 3);
|
|
$expected = is_array($expect) ? $expect : [$expect];
|
|
|
|
if (!in_array($code, $expected, true)) {
|
|
throw new RuntimeException(
|
|
'Erreur SMTP (attendu ' . implode('/', $expected) . ", recu {$code}) : " . trim($response)
|
|
);
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
|
|
/**
|
|
* Encode un header UTF-8 si necessaire.
|
|
*/
|
|
private function encodeHeader(string $value): string
|
|
{
|
|
if (preg_match('/[^\x20-\x7E]/', $value)) {
|
|
return '=?UTF-8?B?' . base64_encode($value) . '?=';
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
|
|
/**
|
|
* Valide une adresse email avant injection SMTP.
|
|
*/
|
|
private function normalizeEmail(string $value): string
|
|
{
|
|
$value = trim(str_replace(["\r", "\n"], '', $value));
|
|
|
|
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
|
|
throw new InvalidArgumentException('Adresse email invalide.');
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
|
|
/**
|
|
* Nettoie les retours a la ligne dans un header texte.
|
|
*/
|
|
private function normalizeHeaderText(string $value): string
|
|
{
|
|
return trim(str_replace(["\r", "\n"], ' ', $value));
|
|
}
|
|
}
|