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

90 lines
2.8 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
'from' => new Parameter('from', Parameter::TYPE_EMAIL),
'to' => new Parameter('to', Parameter::TYPE_EMAIL),
'subject' => new StringType('subject', -1),
'body' => new StringType('body', -1),
'fromName' => new StringType('fromName', -1, true, ''),
'replyTo' => new Parameter('to', Parameter::TYPE_EMAIL, true, ''),
));
$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"];
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"] ?? "";
return new ConnectionData($host, $port, $login, $password);
}
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();
$mail->setFrom($this->getParam('from'), $this->getParam('fromName'));
$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');
$replyTo = $this->getParam('replyTo');
if(!is_null($replyTo) && !empty($replyTo)) {
$mail->AddReplyTo($replyTo, $this->getParam('fromName'));
}
$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
}