| 148 |
lars |
1 |
Mailer Component
|
|
|
2 |
================
|
|
|
3 |
|
|
|
4 |
The Mailer component helps sending emails.
|
|
|
5 |
|
|
|
6 |
Getting Started
|
|
|
7 |
---------------
|
|
|
8 |
|
|
|
9 |
```
|
|
|
10 |
$ composer require symfony/mailer
|
|
|
11 |
```
|
|
|
12 |
|
|
|
13 |
```php
|
|
|
14 |
use Symfony\Component\Mailer\Transport;
|
|
|
15 |
use Symfony\Component\Mailer\Mailer;
|
|
|
16 |
use Symfony\Component\Mime\Email;
|
|
|
17 |
|
|
|
18 |
$transport = Transport::fromDsn('smtp://localhost');
|
|
|
19 |
$mailer = new Mailer($transport);
|
|
|
20 |
|
|
|
21 |
$email = (new Email())
|
|
|
22 |
->from('hello@example.com')
|
|
|
23 |
->to('you@example.com')
|
|
|
24 |
//->cc('cc@example.com')
|
|
|
25 |
//->bcc('bcc@example.com')
|
|
|
26 |
//->replyTo('fabien@example.com')
|
|
|
27 |
//->priority(Email::PRIORITY_HIGH)
|
|
|
28 |
->subject('Time for Symfony Mailer!')
|
|
|
29 |
->text('Sending emails is fun again!')
|
|
|
30 |
->html('<p>See Twig integration for better HTML integration!</p>');
|
|
|
31 |
|
|
|
32 |
$mailer->send($email);
|
|
|
33 |
```
|
|
|
34 |
|
|
|
35 |
To enable the Twig integration of the Mailer, require `symfony/twig-bridge` and
|
|
|
36 |
set up the `BodyRenderer`:
|
|
|
37 |
|
|
|
38 |
```php
|
|
|
39 |
use Symfony\Bridge\Twig\Mime\BodyRenderer;
|
|
|
40 |
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
|
|
|
41 |
use Symfony\Component\EventDispatcher\EventDispatcher;
|
|
|
42 |
use Symfony\Component\Mailer\EventListener\MessageListener;
|
|
|
43 |
use Symfony\Component\Mailer\Mailer;
|
|
|
44 |
use Symfony\Component\Mailer\Transport;
|
|
|
45 |
use Twig\Environment as TwigEnvironment;
|
|
|
46 |
|
|
|
47 |
$twig = new TwigEnvironment(...);
|
|
|
48 |
$messageListener = new MessageListener(null, new BodyRenderer($twig));
|
|
|
49 |
|
|
|
50 |
$eventDispatcher = new EventDispatcher();
|
|
|
51 |
$eventDispatcher->addSubscriber($messageListener);
|
|
|
52 |
|
|
|
53 |
$transport = Transport::fromDsn('smtp://localhost', $eventDispatcher);
|
|
|
54 |
$mailer = new Mailer($transport, null, $eventDispatcher);
|
|
|
55 |
|
|
|
56 |
$email = (new TemplatedEmail())
|
|
|
57 |
// ...
|
|
|
58 |
->htmlTemplate('emails/signup.html.twig')
|
|
|
59 |
->context([
|
|
|
60 |
'expiration_date' => new \DateTime('+7 days'),
|
|
|
61 |
'username' => 'foo',
|
|
|
62 |
])
|
|
|
63 |
;
|
|
|
64 |
$mailer->send($email);
|
|
|
65 |
```
|
|
|
66 |
|
|
|
67 |
Resources
|
|
|
68 |
---------
|
|
|
69 |
|
|
|
70 |
* [Documentation](https://symfony.com/doc/current/mailer.html)
|
|
|
71 |
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
|
|
|
72 |
* [Report issues](https://github.com/symfony/symfony/issues) and
|
|
|
73 |
[send Pull Requests](https://github.com/symfony/symfony/pulls)
|
|
|
74 |
in the [main Symfony repository](https://github.com/symfony/symfony)
|