| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- use PHPMailer\PHPMailer\PHPMailer;
- class Email {
- private $instance;
- private $htmlContent = "";
- // Static functions
- public static function getPHPMailerInstance() {
- $mail = new PHPMailer(true);
- $mail->isSMTP();
- $mail->Host = SMTP_HOST;
- $mail->SMTPAuth = true;
- $mail->Username = SMTP_USERNAME;
- $mail->Password = SMTP_PASSWORD;
- $mail->SMTPSecure = SMTP_AUTHENTICATION_TYPE;
- $mail->Port = SMTP_PORT;
- return $mail;
- }
- public function __construct() {
- $this->instance = Email::getPHPMailerInstance();
- }
- public function loadHtmlTemplate($template_name) {
- $this->instance->IsHTML(true);
- $path = "emails/$template_name.html";
- if(!file_exists($path)) throw new Exception("Email HTML template \"$template_name\" cannot be found.");
- $this->htmlContent = file_get_contents($path);
- }
- public function setValues($values = []) {
- foreach($values as $key => $value) {
- $this->htmlContent = str_replace("{" . $key . "}", $value, $this->htmlContent);
- }
- return true;
- }
- public function setFrom($email, $name="") {
- return $this->instance->setFrom($email, $name);
- }
- public function addAddress($email, $name="") {
- return $this->instance->addAddress($email, $name);
- }
- public function setSubject($subject) {
- $this->instance->Subject = $subject;
- return true;
- }
- public function send() {
- // Does our sanity checks and then send email
- $instance = $this->instance;
- $to_addresses = $instance->getToAddresses();
- if(empty($to_addresses)) throw new Exception("No recipients are set.");
- if(empty($instance->Subject)) throw new Exception("No subject is set.");
- if(empty($this->htmlContent)) throw new Exception("No content is set.");
- $count = preg_match_all("/\{([a-z\-]+)\}/", $this->htmlContent, $matches);
- if($count > 0) {
- $missing_keys = [];
- foreach($matches[1] as $key) {
- $missing_keys[] = $key;
- }
- throw new Exception("Missing values: " . implode(", ", $missing_keys));
- }
- $instance->Body = $this->htmlContent;
- return $this->instance->send();
- }
- }
|