1
0

email.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. $this->htmlContent = file_get_contents($path);
  26. }
  27. public function setValues($values = []) {
  28. foreach($values as $key => $value) {
  29. $this->htmlContent = str_replace("{" . $key . "}", $value, $this->htmlContent);
  30. }
  31. return true;
  32. }
  33. public function setFrom($email, $name="") {
  34. return $this->instance->setFrom($email, $name);
  35. }
  36. public function addAddress($email, $name="") {
  37. return $this->instance->addAddress($email, $name);
  38. }
  39. public function setSubject($subject) {
  40. $this->instance->Subject = $subject;
  41. return true;
  42. }
  43. public function send() {
  44. // Does our sanity checks and then send email
  45. $instance = $this->instance;
  46. $to_addresses = $instance->getToAddresses();
  47. if(empty($to_addresses)) throw new Exception("No recipients are set.");
  48. if(empty($instance->Subject)) throw new Exception("No subject is set.");
  49. if(empty($this->htmlContent)) throw new Exception("No content is set.");
  50. $count = preg_match_all("/\{([a-z\-]+)\}/", $this->htmlContent, $matches);
  51. if($count > 0) {
  52. $missing_keys = [];
  53. foreach($matches[1] as $key) {
  54. $missing_keys[] = $key;
  55. }
  56. throw new Exception("Missing values: " . implode(", ", $missing_keys));
  57. }
  58. $instance->Body = $this->htmlContent;
  59. return $this->instance->send();
  60. }
  61. }