xref: /webtrees/app/Services/EmailService.php (revision 24931b29a0237a5f5f1b8620af661ea530451af0)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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\Registry;
26use Fisharebest\Webtrees\Site;
27use Fisharebest\Webtrees\Validator;
28use Psr\Http\Message\ServerRequestInterface;
29use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
30use Symfony\Component\Mailer\Mailer;
31use Symfony\Component\Mailer\Transport\NullTransport;
32use Symfony\Component\Mailer\Transport\SendmailTransport;
33use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
34use Symfony\Component\Mailer\Transport\TransportInterface;
35use Symfony\Component\Mime\Address;
36use Symfony\Component\Mime\Crypto\DkimOptions;
37use Symfony\Component\Mime\Crypto\DkimSigner;
38use Symfony\Component\Mime\Email;
39use Symfony\Component\Mime\Exception\RfcComplianceException;
40use Symfony\Component\Mime\Message;
41
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 (RfcComplianceException $ex) {
74            Log::addErrorLog('Cannot create email  ' . $ex->getMessage());
75
76            return false;
77        } catch (TransportExceptionInterface $ex) {
78            Log::addErrorLog('Cannot send email: ' . $ex->getMessage());
79
80            return false;
81        }
82
83        return true;
84    }
85
86    /**
87     * Create a message
88     *
89     * @param UserInterface $from
90     * @param UserInterface $to
91     * @param UserInterface $reply_to
92     * @param string        $subject
93     * @param string        $message_text
94     * @param string        $message_html
95     *
96     * @return Message
97     */
98    protected function message(UserInterface $from, UserInterface $to, UserInterface $reply_to, string $subject, string $message_text, string $message_html): Message
99    {
100        // Mail needs MS-DOS line endings
101        $message_text = str_replace("\n", "\r\n", $message_text);
102        $message_html = str_replace("\n", "\r\n", $message_html);
103
104        $message = (new Email())
105            ->subject($subject)
106            ->from(new Address($from->email(), $from->realName()))
107            ->to(new Address($to->email(), $to->realName()))
108            ->replyTo(new Address($reply_to->email(), $reply_to->realName()))
109            ->html($message_html);
110
111        $dkim_domain   = Site::getPreference('DKIM_DOMAIN');
112        $dkim_selector = Site::getPreference('DKIM_SELECTOR');
113        $dkim_key      = Site::getPreference('DKIM_KEY');
114
115        if ($dkim_domain !== '' && $dkim_selector !== '' && $dkim_key !== '') {
116            $signer = new DkimSigner($dkim_key, $dkim_domain, $dkim_selector);
117            $options = (new DkimOptions())
118                ->headerCanon('relaxed')
119                ->bodyCanon('relaxed');
120
121            return $signer->sign($message, $options->toArray());
122        }
123
124        // DKIM body hashes don't work with multipart/alternative content.
125        $message->text($message_text);
126
127        return $message;
128    }
129
130    /**
131     * Create a transport mechanism for sending mail
132     *
133     * @return TransportInterface
134     */
135    protected function transport(): TransportInterface
136    {
137        switch (Site::getPreference('SMTP_ACTIVE')) {
138            case 'sendmail':
139                // Local sendmail (requires PHP proc_* functions)
140                $request          = Registry::container()->get(ServerRequestInterface::class);
141                $sendmail_command = Validator::attributes($request)->string('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 (RfcComplianceException) {
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);
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