44 lines
1.5 KiB
PHP
44 lines
1.5 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
final class MailSender
|
|
{
|
|
public static function buildMessage(string $from, string $to, string $subject, string $body): string
|
|
{
|
|
foreach ([$from, $to, $subject] as $value) {
|
|
if (str_contains($value, "\r") || str_contains($value, "\n")) {
|
|
throw new InvalidArgumentException('Invalid subject or address header');
|
|
}
|
|
}
|
|
$encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
|
|
$headers = [
|
|
'From: ' . $from,
|
|
'To: ' . $to,
|
|
'Subject: ' . $encodedSubject,
|
|
'Auto-Submitted: auto-replied',
|
|
'Content-Type: text/plain; charset=UTF-8',
|
|
'Content-Transfer-Encoding: 8bit',
|
|
];
|
|
return implode("\n", $headers) . "\n\n" . str_replace(["\r\n", "\r"], "\n", $body) . "\n";
|
|
}
|
|
|
|
public function send(string $sendmail, string $from, string $to, string $subject, string $body): bool
|
|
{
|
|
$message = self::buildMessage($from, $to, $subject, $body);
|
|
if (!is_file($sendmail) || !is_executable($sendmail)) {
|
|
return false;
|
|
}
|
|
$process = proc_open([$sendmail, '-t', '-i'], [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
|
|
if (!is_resource($process)) {
|
|
return false;
|
|
}
|
|
fwrite($pipes[0], $message);
|
|
fclose($pipes[0]);
|
|
stream_get_contents($pipes[1]);
|
|
stream_get_contents($pipes[2]);
|
|
fclose($pipes[1]);
|
|
fclose($pipes[2]);
|
|
return proc_close($process) === 0;
|
|
}
|
|
}
|