xref: /webtrees/app/Services/EmailService.php (revision 4991f2057a6647447a648c5d6743dab00378e98e)
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 Fisharebest\Webtrees\Contracts\UserInterface;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Log;
25use Fisharebest\Webtrees\Site;
26use Fisharebest\Webtrees\Validator;
27use Psr\Http\Message\ServerRequestInterface;
28use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
29use Symfony\Component\Mailer\Mailer;
30use Symfony\Component\Mailer\Transport\NullTransport;
31use Symfony\Component\Mailer\Transport\SendmailTransport;
32use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
33use Symfony\Component\Mailer\Transport\TransportInterface;
34use Symfony\Component\Mime\Address;
35use Symfony\Component\Mime\Crypto\DkimOptions;
36use Symfony\Component\Mime\Crypto\DkimSigner;
37use Symfony\Component\Mime\Email;
38use Symfony\Component\Mime\Exception\RfcComplianceException;
39use Symfony\Component\Mime\Message;
40
41use function assert;
42use function checkdnsrr;
43use function function_exists;
44use function str_replace;
45use function strrchr;
46use function substr;
47
48/**
49 * Send emails.
50 */
51class EmailService
52{
53    /**
54     * Send an external email message
55     * Caution! gmail may rewrite the "From" header unless you have added the address to your account.
56     *
57     * @param UserInterface $from
58     * @param UserInterface $to
59     * @param UserInterface $reply_to
60     * @param string        $subject
61     * @param string        $message_text
62     * @param string        $message_html
63     *
64     * @return bool
65     */
66    public function send(UserInterface $from, UserInterface $to, UserInterface $reply_to, string $subject, string $message_text, string $message_html): bool
67    {
68        try {
69            $message   = $this->message($from, $to, $reply_to, $subject, $message_text, $message_html);
70            $transport = $this->transport();
71            $mailer    = new Mailer($transport);
72            $mailer->send($message);
73        } catch (TransportExceptionInterface $ex) {
74            Log::addErrorLog('MailService: ' . $ex->getMessage());
75
76            return false;
77        }
78
79        return true;
80    }
81
82    /**
83     * Create a message
84     *
85     * @param UserInterface $from
86     * @param UserInterface $to
87     * @param UserInterface $reply_to
88     * @param string        $subject
89     * @param string        $message_text
90     * @param string        $message_html
91     *
92     * @return Message
93     */
94    protected function message(UserInterface $from, UserInterface $to, UserInterface $reply_to, string $subject, string $message_text, string $message_html): Message
95    {
96        // Mail needs MS-DOS line endings
97        $message_text = str_replace("\n", "\r\n", $message_text);
98        $message_html = str_replace("\n", "\r\n", $message_html);
99
100        $message = (new Email())
101            ->subject($subject)
102            ->from(new Address($from->email(), $from->realName()))
103            ->to(new Address($to->email(), $to->realName()))
104            ->replyTo(new Address($reply_to->email(), $reply_to->realName()))
105            ->html($message_html);
106
107        $dkim_domain   = Site::getPreference('DKIM_DOMAIN');
108        $dkim_selector = Site::getPreference('DKIM_SELECTOR');
109        $dkim_key      = Site::getPreference('DKIM_KEY');
110
111        if ($dkim_domain !== '' && $dkim_selector !== '' && $dkim_key !== '') {
112            $signer = new DkimSigner($dkim_key, $dkim_domain, $dkim_selector);
113            $options = (new DkimOptions())
114                ->headerCanon('relaxed')
115                ->bodyCanon('relaxed');
116
117            return $signer->sign($message, $options->toArray());
118        }
119
120        // DKIM body hashes don't work with multipart/alternative content.
121        $message->text($message_text);
122
123        return $message;
124    }
125
126    /**
127     * Create a transport mechanism for sending mail
128     *
129     * @return TransportInterface
130     */
131    protected function transport(): TransportInterface
132    {
133        switch (Site::getPreference('SMTP_ACTIVE')) {
134            case 'sendmail':
135                // Local sendmail (requires PHP proc_* functions)
136                $request = app(ServerRequestInterface::class);
137                assert($request instanceof ServerRequestInterface);
138
139                $sendmail_command = Validator::attributes($request)->string('sendmail_command', '/usr/sbin/sendmail -bs');
140
141                return new SendmailTransport($sendmail_command);
142
143            case 'external':
144                // SMTP
145                $smtp_helo = Site::getPreference('SMTP_HELO');
146                $smtp_host = Site::getPreference('SMTP_HOST');
147                $smtp_port = (int) Site::getPreference('SMTP_PORT');
148                $smtp_auth = (bool) Site::getPreference('SMTP_AUTH');
149                $smtp_user = Site::getPreference('SMTP_AUTH_USER');
150                $smtp_pass = Site::getPreference('SMTP_AUTH_PASS');
151                $smtp_encr = Site::getPreference('SMTP_SSL') === 'ssl';
152
153                $transport = new EsmtpTransport($smtp_host, $smtp_port, $smtp_encr);
154
155                $transport->setLocalDomain($smtp_helo);
156
157                if ($smtp_auth) {
158                    $transport
159                        ->setUsername($smtp_user)
160                        ->setPassword($smtp_pass);
161                }
162
163                return $transport;
164
165            default:
166                // For testing
167                return new NullTransport();
168        }
169    }
170
171    /**
172     * Many mail relays require a valid sender email.
173     *
174     * @param string $email
175     *
176     * @return bool
177     */
178    public function isValidEmail(string $email): bool
179    {
180        try {
181            $address = new Address($email);
182        } catch (RfcComplianceException $ex) {
183            return false;
184        }
185
186        // Some web hosts disable checkdnsrr.
187        if (function_exists('checkdnsrr')) {
188            $domain = substr(strrchr($address->getAddress(), '@') ?: '@', 1);
189            return checkdnsrr($domain);
190        }
191
192        return true;
193    }
194
195    /**
196     * A list SSL modes (e.g. for an edit control).
197     *
198     * @return array<string>
199     */
200    public function mailSslOptions(): array
201    {
202        return [
203            'none' => I18N::translate('none'),
204            /* I18N: Use SMTP over SSL/TLS, or Implicit TLS - a secure communications protocol */
205            'ssl'  => I18N::translate('SSL/TLS'),
206            /* I18N: Use SMTP with STARTTLS, or Explicit TLS - a secure communications protocol */
207            'tls'  => I18N::translate('STARTTLS'),
208        ];
209    }
210
211    /**
212     * A list SSL modes (e.g. for an edit control).
213     *
214     * @return array<string>
215     */
216    public function mailTransportOptions(): array
217    {
218        $options = [
219            /* I18N: "sendmail" is the name of some mail software */
220            'sendmail' => I18N::translate('Use sendmail to send messages'),
221            'external' => I18N::translate('Use SMTP to send messages'),
222        ];
223
224        if (!function_exists('proc_open')) {
225            unset($options['sendmail']);
226        }
227
228        return $options;
229    }
230}
231