25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

104 satır
2.5KB

  1. <?php
  2. namespace Framework\Email\Driver;
  3. use Framework\Email\Exception\CompositionException;
  4. use Swift_Mailer;
  5. use Swift_Message;
  6. use Swift_SmtpTransport;
  7. class SmtpDriver implements Driver
  8. {
  9. private array $config;
  10. private Swift_Mailer $mailer;
  11. private string $to;
  12. private string $subject;
  13. private string $text;
  14. private string $html;
  15. public function __construct(array $config)
  16. {
  17. $this->config = $config;
  18. }
  19. public function to(string $to): static
  20. {
  21. $this->to = $to;
  22. return $this;
  23. }
  24. public function subject(string $subject): static
  25. {
  26. $this->subject = $subject;
  27. return $this;
  28. }
  29. public function text(string $text): static
  30. {
  31. $this->text = $text;
  32. return $this;
  33. }
  34. public function html(string $html): static
  35. {
  36. $this->html = $html;
  37. return $this;
  38. }
  39. public function send(): void
  40. {
  41. if (!isset($this->to)) {
  42. throw new CompositionException('to required');
  43. }
  44. if (!isset($this->text) && !isset($this->html)) {
  45. throw new CompositionException('text or email required');
  46. }
  47. $fromName = $this->config['from']['name'];
  48. $fromEmail = $this->config['from']['email'];
  49. $subject = $this->subject ?? "Message from {$fromName}";
  50. $message = (new Swift_Message($subject))
  51. ->setFrom([$fromEmail => $fromName])
  52. ->setTo([$this->to]);
  53. if (isset($this->text) && !isset($this->html)) {
  54. $message->setBody($this->text, 'text/plain');
  55. }
  56. if (!isset($this->text) && isset($this->html)) {
  57. $message->setBody($this->html, 'text/html');
  58. }
  59. if (isset($this->text, $this->html)) {
  60. $message
  61. ->setBody($this->html, 'text/html')
  62. ->addPart($this->text, 'text/plain');
  63. }
  64. $this->mailer()->send($message);
  65. }
  66. private function mailer(): Swift_Mailer
  67. {
  68. if (!isset($this->mailer)) {
  69. $transport = new Swift_SmtpTransport(
  70. $this->config['host'],
  71. $this->config['port'],
  72. $this->config['encryption'] ?: null,
  73. );
  74. if (!empty($this->config['username'])) {
  75. $transport->setUsername($this->config['username']);
  76. $transport->setPassword($this->config['password'] ?? '');
  77. }
  78. $this->mailer = new Swift_Mailer($transport);
  79. }
  80. return $this->mailer;
  81. }
  82. }

Powered by TurnKey Linux.