email.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. use PHPMailer\PHPMailer\PHPMailer;
  3. class Email {
  4. private $instance;
  5. private $htmlContent = "";
  6. // Static functions
  7. public static function getPHPMailerInstance() {
  8. $mail = new PHPMailer(true);
  9. $mail->isSMTP();
  10. $mail->Host = SMTP_HOST;
  11. $mail->SMTPAuth = true;
  12. $mail->Username = SMTP_USERNAME;
  13. $mail->Password = SMTP_PASSWORD;
  14. $mail->SMTPSecure = SMTP_AUTHENTICATION_TYPE;
  15. $mail->Port = SMTP_PORT;
  16. return $mail;
  17. }
  18. public function __construct() {
  19. $this->instance = Email::getPHPMailerInstance();
  20. }
  21. public function loadHtmlTemplate($template_name) {
  22. $this->instance->IsHTML(true);
  23. $path = "emails/$template_name.html";
  24. if(!file_exists($path)) throw new Exception("Email HTML template \"$template_name\" cannot be found.");
  25. $content = file_get_contents($path);
  26. // Embed images
  27. $match_count = preg_match_all("/src\=\"(\.\.\/public\/img\/[^\"]*)\"/i", $content, $all_matches);
  28. if($match_count > 0) {
  29. $paths = $all_matches[1];
  30. foreach($paths as $path) {
  31. $filename = basename($path);
  32. $cid = str_replace(".", "_", $filename);
  33. $path = ltrim($path, "./");
  34. $this->instance->addEmbeddedImage($path, $cid, $filename);
  35. $content = str_replace("../$path", "cid:$cid", $content);
  36. }
  37. }
  38. $this->htmlContent = $content;
  39. }
  40. public function setValues($values = []) {
  41. foreach($values as $key => $value) {
  42. $this->htmlContent = str_replace("{" . $key . "}", $value, $this->htmlContent);
  43. }
  44. return true;
  45. }
  46. public function setFrom($email, $name="") {
  47. return $this->instance->setFrom($email, $name);
  48. }
  49. public function addAddress($email, $name="") {
  50. return $this->instance->addAddress($email, $name);
  51. }
  52. public function setSubject($subject) {
  53. $this->instance->Subject = $subject;
  54. return true;
  55. }
  56. public function send() {
  57. // Does our sanity checks and then send email
  58. $instance = $this->instance;
  59. $to_addresses = $instance->getToAddresses();
  60. if(empty($to_addresses)) throw new Exception("No recipients are set.");
  61. if(empty($instance->Subject)) throw new Exception("No subject is set.");
  62. if(empty($this->htmlContent)) throw new Exception("No content is set.");
  63. $count = preg_match_all("/\{([a-z\-]+)\}/", $this->htmlContent, $matches);
  64. if($count > 0) {
  65. $missing_keys = [];
  66. foreach($matches[1] as $key) {
  67. $missing_keys[] = $key;
  68. }
  69. throw new Exception("Missing values: " . implode(", ", $missing_keys));
  70. }
  71. $instance->Body = $this->htmlContent;
  72. return $this->instance->send();
  73. }
  74. }