Files
project-manager/src/Mail/PhpMailerMailer.php
T

68 lines
1.9 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Mail;
use App\Support\MailConfig;
use PHPMailer\PHPMailer\Exception as PhpMailerException;
use PHPMailer\PHPMailer\PHPMailer;
/**
* Sends via SMTP when MAIL_TRANSPORT=smtp, otherwise via PHP's mail() function.
*/
final class PhpMailerMailer implements Mailer
{
public function __construct(private readonly MailConfig $config)
{
}
public function send(string $to, string $subject, string $body): void
{
$mail = new PHPMailer(true);
try {
if ($this->config->transport === 'smtp') {
$this->configureSmtp($mail);
} else {
$mail->isMail();
}
$mail->setFrom($this->config->fromAddress, $this->config->fromName);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->isHTML(false);
$mail->Body = $body;
$mail->send();
} catch (PhpMailerException $e) {
throw new MailException('Failed to send email: ' . $e->getMessage(), 0, $e);
}
}
private function configureSmtp(PHPMailer $mail): void
{
$mail->isSMTP();
$mail->Host = (string) $this->config->smtpHost;
$mail->Port = $this->config->smtpPort;
if ($this->config->smtpUsername !== null) {
$mail->SMTPAuth = true;
$mail->Username = $this->config->smtpUsername;
$mail->Password = (string) $this->config->smtpPassword;
}
switch ($this->config->smtpEncryption) {
case 'ssl':
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
break;
case 'none':
$mail->SMTPSecure = '';
$mail->SMTPAutoTLS = false;
break;
default:
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
}
}
}