feca-mailshots-plugin/feca_mailshots_plugin/src/Infrastructure/PhpImapAppender.php

51 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace FecaMailshots\Infrastructure;
use FecaMailshots\Application\ImapAppender;
final class PhpImapAppender implements ImapAppender
{
/** @var array<string, bool> */
private array $attemptCache = [];
public function appendSent(array $credentials, string $rawMime, string $attemptId): void
{
if (isset($this->attemptCache[$attemptId])) {
return;
}
$host = (string) ($credentials['imap_host'] ?? '');
$port = (int) ($credentials['imap_port'] ?? 993);
$user = (string) ($credentials['imap_user'] ?? '');
$pass = (string) ($credentials['imap_password'] ?? '');
$folder = (string) ($credentials['imap_sent_folder'] ?? 'Sent');
$flags = (string) ($credentials['imap_mailbox_flags'] ?? '/imap/ssl');
if ($host === '' || $user === '' || $pass === '') {
throw new \RuntimeException('IMAP credentials are missing.');
}
if (!function_exists('imap_open') || !function_exists('imap_append')) {
throw new \RuntimeException('IMAP extension is not available in PHP runtime.');
}
$mailbox = sprintf('{%s:%d%s}%s', $host, $port, $flags, $folder);
$imap = @imap_open($mailbox, $user, $pass);
if ($imap === false) {
throw new \RuntimeException('Failed to open IMAP mailbox: ' . (imap_last_error() ?: 'unknown error'));
}
try {
if (!@imap_append($imap, $mailbox, $rawMime . "\r\n", "\\Seen")) {
throw new \RuntimeException('Failed to append to IMAP Sent folder: ' . (imap_last_error() ?: 'unknown error'));
}
$this->attemptCache[$attemptId] = true;
} finally {
imap_close($imap);
}
}
}