xref: /webtrees/app/Services/EmailService.php (revision 07c504c0924e8d16a326a7ca1bfdb2d3e39e88b8)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22use Exception;
23use Fisharebest\Webtrees\Contracts\UserInterface;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Log;
26use Fisharebest\Webtrees\Site;
27use Psr\Http\Message\ServerRequestInterface;
28use Symfony\Component\Mailer\Mailer;
29use Symfony\Component\Mailer\Transport\NullTransport;
30use Symfony\Component\Mailer\Transport\SendmailTransport;
31use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
32use Symfony\Component\Mailer\Transport\TransportInterface;
33use Symfony\Component\Mime\Address;
34use Symfony\Component\Mime\Crypto\DkimOptions;
35use Symfony\Component\Mime\Crypto\DkimSigner;
36use Symfony\Component\Mime\Email;
37use Symfony\Component\Mime\Message;
38
39use function assert;
40use function checkdnsrr;
41use function filter_var;
42use function function_exists;
43use function str_replace;
44use function strrchr;
45use function substr;
46
47use const FILTER_VALIDATE_DOMAIN;
48use const FILTER_VALIDATE_EMAIL;
49
50/**
51 * Send emails.
52 */
53class EmailService
54{
55    /**
56     * Send an external email message
57     * Caution! gmail may rewrite the "From" header unless you have added the address to your account.
58     *
59     * @param UserInterface $from
60     * @param UserInterface $to
61     * @param UserInterface $reply_to
62     * @param string        $subject
63     * @param string        $message_text
64     * @param string        $message_html
65     *
66     * @return bool
67     */
68    public function send(UserInterface $from, UserInterface $to, UserInterface $reply_to, string $subject, string $message_text, string $message_html): bool
69    {
70        try {
71            $message   = $this->message($from, $to, $reply_to, $subject, $message_text, $message_html);
72            $transport = $this->transport();
73            $mailer    = new Mailer($transport);
74            $mailer->send($message);
75        } catch (Exception $ex) {
76            Log::addErrorLog('MailService: ' . $ex->getMessage());
77
78            return false;
79        }
80
81        return true;
82    }
83
84    /**
85     * Create a message
86     *
87     * @param UserInterface $from
88     * @param UserInterface $to
89     * @param UserInterface $reply_to
90     * @param string        $subject
91     * @param string        $message_text
92     * @param string        $message_html
93     *
94     * @return Message
95     */
96    protected function message(UserInterface $from, UserInterface $to, UserInterface $reply_to, string $subject, string $message_text, string $message_html): Message
97    {
98        // Mail needs MS-DOS line endings
99        $message_text = str_replace("\n", "\r\n", $message_text);
100        $message_html = str_replace("\n", "\r\n", $message_html);
101
102        $message = (new Email())
103            ->subject($subject)
104            ->from(new Address($from->email(), $from->realName()))
105            ->to(new Address($to->email(), $to->realName()))
106            ->replyTo(new Address($reply_to->email(), $reply_to->realName()))
107            ->html($message_html);
108
109        $dkim_domain   = Site::getPreference('DKIM_DOMAIN');
110        $dkim_selector = Site::getPreference('DKIM_SELECTOR');
111        $dkim_key      = Site::getPreference('DKIM_KEY');
112
113        if ($dkim_domain !== '' && $dkim_selector !== '' && $dkim_key !== '') {
114            $signer = new DkimSigner($dkim_key, $dkim_domain, $dkim_selector);
115            $options = (new DkimOptions())
116                ->headerCanon('relaxed')
117                ->bodyCanon('relaxed');
118
119            return $signer->sign($message, $options->toArray());
120        } else {
121            // DKIM body hashes don't work with multipart/alternative content.
122            $message->text($message_text);
123        }
124
125        return $message;
126    }
127
128    /**
129     * Create a transport mechanism for sending mail
130     *
131     * @return TransportInterface
132     */
133    protected function transport(): TransportInterface
134    {
135        switch (Site::getPreference('SMTP_ACTIVE')) {
136            case 'sendmail':
137                // Local sendmail (requires PHP proc_* functions)
138                $request = app(ServerRequestInterface::class);
139                assert($request instanceof ServerRequestInterface);
140
141                $sendmail_command = $request->getAttribute('sendmail_command', '/usr/sbin/sendmail -bs');
142
143                return new SendmailTransport($sendmail_command);
144
145            case 'external':
146                // SMTP
147                $smtp_helo = Site::getPreference('SMTP_HELO');
148                $smtp_host = Site::getPreference('SMTP_HOST');
149                $smtp_port = (int) Site::getPreference('SMTP_PORT');
150                $smtp_auth = (bool) Site::getPreference('SMTP_AUTH');
151                $smtp_user = Site::getPreference('SMTP_AUTH_USER');
152                $smtp_pass = Site::getPreference('SMTP_AUTH_PASS');
153                $smtp_encr = Site::getPreference('SMTP_SSL') === 'ssl';
154
155                $transport = new EsmtpTransport($smtp_host, $smtp_port, $smtp_encr);
156
157                $transport->setLocalDomain($smtp_helo);
158
159                if ($smtp_auth) {
160                    $transport
161                        ->setUsername($smtp_user)
162                        ->setPassword($smtp_pass);
163                }
164
165                return $transport;
166
167            default:
168                // For testing
169                return new NullTransport();
170        }
171    }
172
173    /**
174     * Many mail relays require a valid sender email.
175     *
176     * @param string $email
177     *
178     * @return bool
179     */
180    public function isValidEmail(string $email): bool
181    {
182        try {
183            $address = new Address($email);
184        } catch (Exception $ex) {
185            return false;
186        }
187
188        // Some web hosts disable checkdnsrr.
189        if (function_exists('checkdnsrr')) {
190            $domain = substr(strrchr($address->getAddress(), '@') ?: '@', 1);
191            return checkdnsrr($domain, 'MX');
192        }
193
194        return true;
195    }
196
197    /**
198     * A list SSL modes (e.g. for an edit control).
199     *
200     * @return array<string>
201     */
202    public function mailSslOptions(): array
203    {
204        return [
205            'none' => I18N::translate('none'),
206            /* I18N: Use SMTP over SSL/TLS, or Implicit TLS - a secure communications protocol */
207            'ssl'  => I18N::translate('SSL/TLS'),
208            /* I18N: Use SMTP with STARTTLS, or Explicit TLS - a secure communications protocol */
209            'tls'  => I18N::translate('STARTTLS'),
210        ];
211    }
212
213    /**
214     * A list SSL modes (e.g. for an edit control).
215     *
216     * @return array<string>
217     */
218    public function mailTransportOptions(): array
219    {
220        $options = [
221            /* I18N: "sendmail" is the name of some mail software */
222            'sendmail' => I18N::translate('Use sendmail to send messages'),
223            'external' => I18N::translate('Use SMTP to send messages'),
224        ];
225
226        if (!function_exists('proc_open')) {
227            unset($options['sendmail']);
228        }
229
230        return $options;
231    }
232}
233