3 namespace Drupal\Tests\system\Functional\Mail;
5 use Drupal\Component\Utility\Random;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Mail\MailFormatHelper;
8 use Drupal\Core\Mail\Plugin\Mail\TestMailCollector;
9 use Drupal\Core\Render\Markup;
11 use Drupal\file\Entity\File;
12 use Drupal\Tests\BrowserTestBase;
13 use Drupal\system_mail_failure_test\Plugin\Mail\TestPhpMailFailure;
16 * Performs tests on the pluggable mailing framework.
20 class MailTest extends BrowserTestBase {
27 public static $modules = ['simpletest', 'system_mail_failure_test', 'mail_html_test', 'file', 'image'];
30 * Assert that the pluggable mail system is functional.
32 public function testPluggableFramework() {
33 // Switch mail backends.
34 $this->config('system.mail')->set('interface.default', 'test_php_mail_failure')->save();
36 // Get the default MailInterface class instance.
37 $mail_backend = \Drupal::service('plugin.manager.mail')->getInstance(['module' => 'default', 'key' => 'default']);
39 // Assert whether the default mail backend is an instance of the expected
41 $this->assertTrue($mail_backend instanceof TestPhpMailFailure, 'Default mail interface can be swapped.');
43 // Add a module-specific mail backend.
44 $this->config('system.mail')->set('interface.mymodule_testkey', 'test_mail_collector')->save();
46 // Get the added MailInterface class instance.
47 $mail_backend = \Drupal::service('plugin.manager.mail')->getInstance(['module' => 'mymodule', 'key' => 'testkey']);
49 // Assert whether the added mail backend is an instance of the expected
51 $this->assertTrue($mail_backend instanceof TestMailCollector, 'Additional mail interfaces can be added.');
55 * Test that message sending may be canceled.
57 * @see simpletest_mail_alter()
59 public function testCancelMessage() {
60 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
62 // Use the state system collector mail backend.
63 $this->config('system.mail')->set('interface.default', 'test_mail_collector')->save();
64 // Reset the state variable that holds sent messages.
65 \Drupal::state()->set('system.test_mail_collector', []);
67 // Send a test message that simpletest_mail_alter should cancel.
68 \Drupal::service('plugin.manager.mail')->mail('simpletest', 'cancel_test', 'cancel@example.com', $language_interface->getId());
69 // Retrieve sent message.
70 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
71 $sent_message = end($captured_emails);
73 // Assert that the message was not actually sent.
74 $this->assertFalse($sent_message, 'Message was canceled.');
78 * Checks the From: and Reply-to: headers.
80 public function testFromAndReplyToHeader() {
81 $language = \Drupal::languageManager()->getCurrentLanguage();
83 // Use the state system collector mail backend.
84 $this->config('system.mail')->set('interface.default', 'test_mail_collector')->save();
85 // Reset the state variable that holds sent messages.
86 \Drupal::state()->set('system.test_mail_collector', []);
87 // Send an email with a reply-to address specified.
88 $from_email = 'Drupal <simpletest@example.com>';
89 $reply_email = 'someone_else@example.com';
90 \Drupal::service('plugin.manager.mail')->mail('simpletest', 'from_test', 'from_test@example.com', $language, [], $reply_email);
91 // Test that the reply-to email is just the email and not the site name
92 // and default sender email.
93 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
94 $sent_message = end($captured_emails);
95 $this->assertEqual($from_email, $sent_message['headers']['From'], 'Message is sent from the site email account.');
96 $this->assertEqual($reply_email, $sent_message['headers']['Reply-to'], 'Message reply-to headers are set.');
97 $this->assertFalse(isset($sent_message['headers']['Errors-To']), 'Errors-to header must not be set, it is deprecated.');
99 // Test that long site names containing characters that need MIME encoding
100 // works as expected.
101 $this->config('system.site')->set('name', 'Drépal this is a very long test sentence to test what happens with very long site names')->save();
102 // Send an email and check that the From-header contains the site name.
103 \Drupal::service('plugin.manager.mail')->mail('simpletest', 'from_test', 'from_test@example.com', $language);
104 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
105 $sent_message = end($captured_emails);
106 $this->assertEquals('=?UTF-8?B?RHLDqXBhbCB0aGlzIGlzIGEgdmVyeSBsb25nIHRlc3Qgc2VudGVuY2UgdG8gdGU=?= <simpletest@example.com>', $sent_message['headers']['From'], 'From header is correctly encoded.');
107 $this->assertEquals('Drépal this is a very long test sentence to te <simpletest@example.com>', Unicode::mimeHeaderDecode($sent_message['headers']['From']), 'From header is correctly encoded.');
108 $this->assertFalse(isset($sent_message['headers']['Reply-to']), 'Message reply-to is not set if not specified.');
109 $this->assertFalse(isset($sent_message['headers']['Errors-To']), 'Errors-to header must not be set, it is deprecated.');
111 // Test RFC-2822 rules are respected for 'display-name' component of
112 // 'From:' header. Specials characters are not allowed, so randomly add one
113 // of them to the site name and check the string is wrapped in quotes. Also
114 // hardcode some double-quotes and backslash to validate these are escaped
116 $specials = '()<>[]:;@\,."';
117 $site_name = 'Drupal' . $specials[rand(0, strlen($specials) - 1)] . ' "si\te"';
118 $this->config('system.site')->set('name', $site_name)->save();
119 // Send an email and check that the From-header contains the site name
120 // within double-quotes. Also make sure double-quotes and "\" are escaped.
121 \Drupal::service('plugin.manager.mail')->mail('simpletest', 'from_test', 'from_test@example.com', $language);
122 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
123 $sent_message = end($captured_emails);
124 $escaped_site_name = str_replace(['\\', '"'], ['\\\\', '\\"'], $site_name);
125 $this->assertEquals('"' . $escaped_site_name . '" <simpletest@example.com>', $sent_message['headers']['From'], 'From header is correctly quoted.');
127 // Make sure display-name is not quoted nor escaped if part on an encoding.
128 $site_name = 'Drépal, "si\te"';
129 $this->config('system.site')->set('name', $site_name)->save();
130 // Send an email and check that the From-header contains the site name.
131 \Drupal::service('plugin.manager.mail')->mail('simpletest', 'from_test', 'from_test@example.com', $language);
132 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
133 $sent_message = end($captured_emails);
134 $this->assertEquals('=?UTF-8?B?RHLDqXBhbCwgInNpXHRlIg==?= <simpletest@example.com>', $sent_message['headers']['From'], 'From header is correctly encoded.');
135 $this->assertEquals($site_name . ' <simpletest@example.com>', Unicode::mimeHeaderDecode($sent_message['headers']['From']), 'From header is correctly encoded.');
139 * Checks that relative paths in mails are converted into absolute URLs.
141 public function testConvertRelativeUrlsIntoAbsolute() {
142 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
144 // Use the HTML compatible state system collector mail backend.
145 $this->config('system.mail')->set('interface.default', 'test_html_mail_collector')->save();
147 // Fetch the hostname and port for matching against.
148 $http_host = \Drupal::request()->getSchemeAndHttpHost();
151 $random = new Random();
153 // One random tag name.
154 $tag_name = strtolower($random->name(8, TRUE));
156 // Test root relative urls.
157 foreach (['href', 'src'] as $attribute) {
158 // Reset the state variable that holds sent messages.
159 \Drupal::state()->set('system.test_mail_collector', []);
161 $html = "<$tag_name $attribute=\"/root-relative\">root relative url in mail test</$tag_name>";
162 $expected_html = "<$tag_name $attribute=\"{$http_host}/root-relative\">root relative url in mail test</$tag_name>";
164 // Prepare render array.
165 $render = ['#markup' => Markup::create($html)];
167 // Send a test message that simpletest_mail_alter should cancel.
168 \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
169 // Retrieve sent message.
170 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
171 $sent_message = end($captured_emails);
173 // Wrap the expected HTML and assert.
174 $expected_html = MailFormatHelper::wrapMail($expected_html);
175 $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
178 // Test protocol relative urls.
179 foreach (['href', 'src'] as $attribute) {
180 // Reset the state variable that holds sent messages.
181 \Drupal::state()->set('system.test_mail_collector', []);
183 $html = "<$tag_name $attribute=\"//example.com/protocol-relative\">protocol relative url in mail test</$tag_name>";
184 $expected_html = "<$tag_name $attribute=\"//example.com/protocol-relative\">protocol relative url in mail test</$tag_name>";
186 // Prepare render array.
187 $render = ['#markup' => Markup::create($html)];
189 // Send a test message that simpletest_mail_alter should cancel.
190 \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
191 // Retrieve sent message.
192 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
193 $sent_message = end($captured_emails);
195 // Wrap the expected HTML and assert.
196 $expected_html = MailFormatHelper::wrapMail($expected_html);
197 $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
200 // Test absolute urls.
201 foreach (['href', 'src'] as $attribute) {
202 // Reset the state variable that holds sent messages.
203 \Drupal::state()->set('system.test_mail_collector', []);
205 $html = "<$tag_name $attribute=\"http://example.com/absolute\">absolute url in mail test</$tag_name>";
206 $expected_html = "<$tag_name $attribute=\"http://example.com/absolute\">absolute url in mail test</$tag_name>";
208 // Prepare render array.
209 $render = ['#markup' => Markup::create($html)];
211 // Send a test message that simpletest_mail_alter should cancel.
212 \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
213 // Retrieve sent message.
214 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
215 $sent_message = end($captured_emails);
217 // Wrap the expected HTML and assert.
218 $expected_html = MailFormatHelper::wrapMail($expected_html);
219 $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$attribute} is properly converted for mails.");
224 * Checks that mails built from render arrays contain absolute paths.
226 * By default Drupal uses relative paths for images and links. When sending
227 * emails, absolute paths should be used instead.
229 public function testRenderedElementsUseAbsolutePaths() {
230 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
232 // Use the HTML compatible state system collector mail backend.
233 $this->config('system.mail')->set('interface.default', 'test_html_mail_collector')->save();
235 // Fetch the hostname and port for matching against.
236 $http_host = \Drupal::request()->getSchemeAndHttpHost();
239 $random = new Random();
240 $image_name = $random->name();
242 // Create an image file.
243 $file = File::create(['uri' => "public://{$image_name}.png", 'filename' => "{$image_name}.png"]);
246 $base_path = base_path();
249 'root relative' => [$file->getFileUri(), "{$http_host}{$base_path}{$this->publicFilesDirectory}/{$image_name}.png"],
250 'protocol relative' => ['//example.com/image.png', '//example.com/image.png'],
251 'absolute' => ['http://example.com/image.png', 'http://example.com/image.png'],
255 foreach ($path_pairs as $test_type => $paths) {
256 list($input_path, $expected_path) = $paths;
258 // Reset the state variable that holds sent messages.
259 \Drupal::state()->set('system.test_mail_collector', []);
261 // Build the render array.
264 '#uri' => $input_path,
266 $expected_html = "<img src=\"$expected_path\" alt=\"\" />";
268 // Send a test message that simpletest_mail_alter should cancel.
269 \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
270 // Retrieve sent message.
271 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
272 $sent_message = end($captured_emails);
274 // Wrap the expected HTML and assert.
275 $expected_html = MailFormatHelper::wrapMail($expected_html);
276 $this->assertSame($expected_html, $sent_message['body'], "Asserting that {$test_type} paths are converted properly.");
281 'root relative' => [Url::fromUserInput('/path/to/something'), "{$http_host}{$base_path}path/to/something"],
282 'protocol relative' => [Url::fromUri('//example.com/image.png'), '//example.com/image.png'],
283 'absolute' => [Url::fromUri('http://example.com/image.png'), 'http://example.com/image.png'],
286 foreach ($path_pairs as $paths) {
287 list($input_path, $expected_path) = $paths;
289 // Reset the state variable that holds sent messages.
290 \Drupal::state()->set('system.test_mail_collector', []);
292 // Build the render array.
296 '#url' => $input_path,
298 $expected_html = "<a href=\"$expected_path\">Link</a>";
300 // Send a test message that simpletest_mail_alter should cancel.
301 \Drupal::service('plugin.manager.mail')->mail('mail_html_test', 'render_from_message_param', 'relative_url@example.com', $language_interface->getId(), ['message' => $render]);
302 // Retrieve sent message.
303 $captured_emails = \Drupal::state()->get('system.test_mail_collector');
304 $sent_message = end($captured_emails);
306 // Wrap the expected HTML and assert.
307 $expected_html = MailFormatHelper::wrapMail($expected_html);
308 $this->assertSame($expected_html, $sent_message['body']);