3 * Name: PHP Mailer SMTP
4 * Description: Connects to a SMTP server based on the config
6 * Author: Marcus Mueller
7 * Maintainer: Hypolite Petovan <hypolite@friendica.mrpetovan.com>
11 use Friendica\Core\Hook;
13 use Friendica\Object\EMail\IEmail;
14 use Friendica\Util\ConfigFileLoader;
15 use PHPMailer\PHPMailer\PHPMailer;
16 use PHPMailer\PHPMailer\Exception;
18 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
20 function phpmailer_install()
22 Hook::register('load_config' , __FILE__, 'phpmailer_load_config');
23 Hook::register('emailer_send_prepare', __FILE__, 'phpmailer_emailer_send_prepare');
26 function phpmailer_load_config(App $a, ConfigFileLoader $loader)
28 $a->getConfigCache()->load($loader->loadAddonConfig('phpmailer'));
33 * @param IEmail $email
35 function phpmailer_emailer_send_prepare(App $a, IEmail &$email)
37 // Passing `true` enables exceptions
38 $mailer = new PHPMailer(true);
40 if (DI::config()->get('phpmailer', 'smtp')) {
41 // Set mailer to use SMTP
45 $mailer->CharSet = 'UTF-8';
46 $mailer->Encoding = 'base64';
48 // Specify main and backup SMTP servers
49 $mailer->Host = DI::config()->get('phpmailer', 'smtp_server');
50 $mailer->Port = DI::config()->get('phpmailer', 'smtp_port');
52 if (DI::config()->get('system', 'smtp_secure') && DI::config()->get('phpmailer', 'smtp_port_s')) {
53 $mailer->SMTPSecure = DI::config()->get('phpmailer', 'smtp_secure');
54 $mailer->Port = DI::config()->get('phpmailer', 'smtp_port_s');
57 if (DI::config()->get('phpmailer', 'smtp_username') && DI::config()->get('phpmailer', 'smtp_password')) {
58 $mailer->SMTPAuth = true;
59 $mailer->Username = DI::config()->get('phpmailer', 'smtp_username');
60 $mailer->Password = DI::config()->get('phpmailer', 'smtp_password');
63 if (DI::config()->get('phpmailer', 'smtp_from')) {
64 $mailer->setFrom(DI::config()->get('phpmailer', 'smtp_from'), $email->getFromName());
67 $mailer->setFrom($email->getFromAddress(), $email->getFromName());
71 $mailer->Subject = $email->getSubject();
73 if (!empty($email->getToAddress())) {
74 $mailer->addAddress($email->getToAddress());
78 if (!empty($email->getMessage())) {
79 $mailer->isHTML(true);
80 $mailer->Body = $email->getMessage();
81 $mailer->AltBody = $email->getMessage(true);
84 $mailer->Body = $email->getMessage(true);
87 if (!empty($email->getReplyTo())) {
88 $mailer->addReplyTo($email->getReplyTo(), $email->getFromName());
92 if (!empty($email->getAdditionalMailHeader())) {
93 foreach (explode("\n", trim($email->getAdditionalMailHeader())) as $header_line) {
94 list($name, $value) = explode(':', $header_line, 2);
95 $mailer->addCustomHeader(trim($name), trim($value));
99 if ($mailer->send()) {
102 } catch (Exception $e) {
103 DI::logger()->error('PHPMailer error', ['email' => $email, 'ErrorInfo' => $mailer->ErrorInfo, 'exception' => $e]);