web-base/core/Api/SendMail.class.php

85 lines
2.5 KiB
PHP
Raw Normal View History

2020-02-10 12:16:34 +01:00
<?php
namespace Api;
use Api\Parameter\Parameter;
use Api\Parameter\StringType;
2020-04-03 15:56:04 +02:00
use External\PHPMailer\Exception;
use External\PHPMailer\PHPMailer;
2020-06-25 16:54:58 +02:00
use Objects\ConnectionData;
2020-02-10 12:16:34 +01:00
class SendMail extends Request {
2020-04-03 15:56:04 +02:00
public function __construct($user, $externalCall = false) {
parent::__construct($user, $externalCall, array(
2020-02-10 12:16:34 +01:00
'to' => new Parameter('to', Parameter::TYPE_EMAIL),
'subject' => new StringType('subject', -1),
'body' => new StringType('body', -1),
));
$this->isPublic = false;
}
2020-06-25 16:54:58 +02:00
private function getMailConfig() : ?ConnectionData {
$req = new \Api\Settings\Get($this->user);
$this->success = $req->execute(array("key" => "^mail_"));
$this->lastError = $req->getLastError();
if ($this->success) {
$settings = $req->getResult()["settings"];
2020-06-26 14:58:17 +02:00
2020-06-25 16:54:58 +02:00
if (!isset($settings["mail_enabled"]) || $settings["mail_enabled"] !== "1") {
$this->createError("Mail is not configured yet.");
return null;
}
$host = $settings["mail_host"] ?? "localhost";
$port = intval($settings["mail_port"] ?? "25");
$login = $settings["mail_username"] ?? "";
$password = $settings["mail_password"] ?? "";
2020-06-26 14:58:17 +02:00
$connectionData = new ConnectionData($host, $port, $login, $password);
$connectionData->setProperty("from", $settings["mail_from"] ?? "");
return $connectionData;
2020-06-25 16:54:58 +02:00
}
return null;
}
2020-02-10 12:16:34 +01:00
public function execute($values = array()) {
if(!parent::execute($values)) {
return false;
}
2020-06-25 16:54:58 +02:00
$mailConfig = $this->getMailConfig();
if (!$this->success) {
return false;
}
2020-06-17 21:39:46 +02:00
2020-06-25 16:54:58 +02:00
try {
2020-04-03 15:56:04 +02:00
$mail = new PHPMailer;
$mail->IsSMTP();
2020-06-26 14:58:17 +02:00
$mail->setFrom($mailConfig->getProperty("from"));
2020-04-03 15:56:04 +02:00
$mail->addAddress($this->getParam('to'));
$mail->Subject = $this->getParam('subject');
$mail->SMTPDebug = 0;
$mail->Host = $mailConfig->getHost();
$mail->Port = $mailConfig->getPort();
$mail->SMTPAuth = true;
$mail->Username = $mailConfig->getLogin();
$mail->Password = $mailConfig->getPassword();
$mail->SMTPSecure = 'tls';
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Body = $this->getParam('body');
$this->success = @$mail->Send();
if (!$this->success) {
$this->lastError = "Error sending Mail: $mail->ErrorInfo";
error_log("sendMail() failed: $mail->ErrorInfo");
}
} catch (Exception $e) {
$this->success = false;
$this->lastError = "Error sending Mail: $e";
2020-02-10 12:16:34 +01:00
}
return $this->success;
}
2020-04-03 15:56:04 +02:00
}