-
-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy path@home.texy
318 lines (228 loc) · 9.44 KB
/
@home.texy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
Sending Emails
**************
<div class=perex>
Are you going to send emails such as newsletters or order confirmations? Nette Framework provides the necessary tools with a very nice API. We will show:
- how to create an email, including attachments
- how to send it
- how to combine emails and templates
</div>
Installation
============
Download and install the package using [Composer|best-practices:composer]:
```shell
composer require nette/mail
```
Creating Emails
===============
Email is a [api:Nette\Mail\Message] object:
```php
$mail = new Nette\Mail\Message;
$mail->setFrom('John <john@example.com>')
->addTo('peter@example.com')
->addTo('jack@example.com')
->setSubject('Order Confirmation')
->setBody("Hello, Your order has been accepted.");
```
All parameters must be encoded in UTF-8.
In addition to specifying recipients with the `addTo()` method, you can also specify the recipient of copy with `addCc()`, or the recipient of blind copy with `addBcc()`. All these methods, including `setFrom()`, accepts addressee in three ways:
```php
$mail->setFrom('john.doe@example.com');
$mail->setFrom('john.doe@example.com', 'John Doe');
$mail->setFrom('John Doe <john.doe@example.com>');
```
The body of an email written in HTML is passed using the `setHtmlBody()` method:
```php
$mail->setHtmlBody('<p>Hello,</p><p>Your order has been accepted.</p>');
```
You don't have to create a text alternative, Nette will generate it automatically for you. And if the email does not have a subject set, it will be taken from the `<title>` element.
Images can also be extremely easily inserted into the HTML body of an email. Just pass the path where the images are physically located as the second parameter, and Nette will automatically include them in the email:
```php
// automatically adds /path/to/images/background.gif to the email
$mail->setHtmlBody(
'<b>Hello</b> <img src="background.gif">',
'/path/to/images',
);
```
The image embedding algorithm supports the following patterns: `<img src=...>`, `<body background=...>`, `url(...)` inside the HTML attribute `style` and special syntax `[[...]]`.
Can sending emails be even easier?
Emails are like postcards. Never send passwords or other credentials via email. .[tip]
Attachments
-----------
You can, of course, attach attachments to email. Use the `addAttachment(string $file, ?string $content = null, ?string $contentType = null)`.
```php
// inserts the file /path/to/example.zip into the email under the name example.zip
$mail->addAttachment('/path/to/example.zip');
// inserts the file /path/to/example.zip into the email under the name info.zip
$mail->addAttachment('info.zip', file_get_contents('/path/to/example.zip'));
// attaches new example.txt file contents "Hello John!"
$mail->addAttachment('example.txt', 'Hello John!');
```
Templates
---------
If you send HTML emails, it's a great idea to write them in the [Latte|latte:] template system. How to do it?
```php
$latte = new Latte\Engine;
$params = [
'orderId' => 123,
];
$mail = new Nette\Mail\Message;
$mail->setFrom('John <john@example.com>')
->addTo('jack@example.com')
->setHtmlBody(
$latte->renderToString('/path/to/email.latte', $params),
'/path/to/images',
);
```
File `email.latte`:
```latte
<html>
<head>
<meta charset="utf-8">
<title>Order Confirmation</title>
<style>
body {
background: url("background.png")
}
</style>
</head>
<body>
<p>Hello,</p>
<p>Your order number {$orderId} has been accepted.</p>
</body>
</html>
```
Nette automatically inserts all images, sets the subject according to the `<title>` element, and generates text alternative for HTML body.
Using in Nette Application
--------------------------
If you use e-mails together with Nette Application, ie presenters, you may want to create links in templates using the `n:href` attribute or the `{link}` tag. Latte basically does not know them, but it's very easy to add them. Creating links can do object `Nette\Application\LinkGenerator`, which you get by passing it using [dependency injection |dependency-injection:passing-dependencies].
```php
use Nette;
class MailSender
{
public function __construct(
private Nette\Application\LinkGenerator $linkGenerator,
private Nette\Bridges\ApplicationLatte\TemplateFactory $templateFactory,
) {
}
private function createTemplate(): Nette\Application\UI\Template
{
$template = $this->templateFactory->createTemplate();
$template->getLatte()->addProvider('uiControl', $this->linkGenerator);
return $template;
}
public function createEmail(): Nette\Mail\Message
{
$template = $this->createTemplate();
$html = $template->renderToString('/path/to/email.latte', $params);
$mail = new Nette\Mail\Message;
$mail->setHtmlBody($html);
// ...
return $mail;
}
}
```
In the template, link is created like in a normal template. All links create over LinkGenerator are absolute:
```latte
<a n:href="Presenter:action">Link</a>
```
Sending Emails
==============
Mailer is class responsible for sending emails. It implements the [api:Nette\Mail\Mailer] interface and several ready-made mailers are available which we will introduce.
The framework automatically adds a `Nette\Mail\Mailer` service based on [configuration|#Configuring] to the DI container, which you get by passing it using [dependency injection |dependency-injection:passing-dependencies].
SendmailMailer
--------------
The default mailer is SendmailMailer which uses PHP function [php:mail]. Example of use:
```php
$mailer = new Nette\Mail\SendmailMailer;
$mailer->send($mail);
```
If you want to set `returnPath` and the server still overwrites it, use `$mailer->commandArgs = '-fmy@email.com'`.
SmtpMailer
----------
To send mail via the SMTP server, use `SmtpMailer`.
```php
$mailer = new Nette\Mail\SmtpMailer(
host: 'smtp.gmail.com',
username: 'franta@gmail.com',
password: '*****',
encryption: 'ssl',
);
$mailer->send($mail);
```
The following additional parameters can be passed to the constructor:
* `port` - if not set, the default 25 or 465 for `ssl` will be used
* `timeout` - timeout for SMTP connection
* `persistent` - use persistent connection
* `clientHost` - client designation
* `streamOptions` - allows you to set "SSL context options":https://www.php.net/manual/en/context.ssl.php for connection
FallbackMailer
--------------
It does not send email but sends them through a set of mailers. If one mailer fails, it repeats the attempt at the next one. If the last one fails, it starts again from the first one.
```php
$mailer = new Nette\Mail\FallbackMailer([
$smtpMailer,
$backupSmtpMailer,
$sendmailMailer,
]);
$mailer->send($mail);
```
Other parameters in the constructor include the number of repeat and waiting time in milliseconds.
DKIM
====
DKIM (DomainKeys Identified Mail) is a trustworthy email technology that also helps detect spoofed messages. The sent message is signed with the private key of the sender's domain and this signature is stored in the email header.
The recipient's server compares this signature with the public key stored in the domain's DNS records. By matching the signature, it is shown that the email actually originated from the sender's domain and that the message was not modified during the transmission of the message.
You can set up mailer to sign email in [configuration|#Configuring]. If you do not use dependency injection, it is used as follows:
```php
$signer = new Nette\Mail\DkimSigner(
domain: 'nette.org',
selector: 'dkim',
privateKey: file_get_contents('../dkim/dkim.key'),
passPhrase: '****',
);
$mailer = new Nette\Mail\SendmailMailer; // or SmtpMailer
$mailer->setSigner($signer);
$mailer->send($mail);
```
Configuring
===========
Overview of configuration options for the Nette Mail. If you are not using the whole framework, but only this library, read [how to load the configuration|bootstrap:].
By default, the mailer `Nette\Mail\SendmailMailer` is used to send emails, which is not further configured. However, we can switch it to `Nette\Mail\SmtpMailer`:
```neon
mail:
# use SmtpMailer
smtp: true # (bool) defaults to false
host: ... # (string)
port: ... # (int)
username: ... # (string)
password: ... # (string)
timeout: ... # (int)
encryption: ... # (ssl|tls|null) defaults to null (has alias 'secure')
clientHost: ... # (string) defaults to $_SERVER['HTTP_HOST']
persistent: ... # (bool) defaults to false
# context for connecting to the SMTP server, defaults to stream_context_get_default()
context:
ssl: # all options at https://www.php.net/manual/en/context.ssl.php
allow_self_signed: ...
...
http: # all options at https://www.php.net/manual/en/context.http.php
header: ...
...
```
You can disable SSL certificate authentication using the `context › ssl › verify_peer: false` option. It is **strongly recommended not to do** this as it will make the application vulnerable. Instead, "add certificates to trust store":https://www.php.net/manual/en/openssl.configuration.php.
To increase trustfulness, we can sign emails using [DKIM technology |https://blog.nette.org/en/sign-emails-with-dkim]:
```neon
mail:
dkim:
domain: myweb.com
selector: lovenette
privateKey: %appDir%/cert/dkim.priv
passPhrase: ...
```
DI Services
===========
These services are added to the DI container:
| Name | Type | Description
|-----------------------------------------------------
| `mail.mailer`| [api:Nette\Mail\Mailer] | [email sending class |#Sending Emails]
| `mail.signer`| [api:Nette\Mail\Signer] | [DKIM signing |#DKIM]
{{leftbar: nette:@menu-topics}}