Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,68 @@ All notable changes to `initphp/mailer` are documented here. The format is
based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Security

- A CR, LF or NUL in an address, display name or return path is now rejected
with an `InvalidAddressException` **whether or not** the `validate` option is
on (`Address`, `setFrom()`, `setReplyTo()`, `setTo()`, `setCC()`, `setBCC()`).
Before, `validate => false` also switched off the only line-break check, so a
request-supplied address could add headers or SMTP commands. Leading and
trailing line breaks are still trimmed, and a recipient string is still split
on whitespace.
- `setHeader()` throws a `MailerException` for a header name containing a CR, LF
or NUL. A header value keeps its documented behaviour: CR and LF are stripped,
and NUL is now stripped too. The subject is stripped of NUL as well.
- Attachment names, dispositions and MIME types containing a CR, LF or NUL throw
an `AttachmentException`; the `userAgent` and `charset` options containing one
throw a `ConfigurationException`.
- `SmtpTransport` refuses a recipient containing a CR, LF, NUL, `<` or `>`
(`InvalidAddressException`) or a client hostname containing a CR, LF or NUL
(`TransportException`) before it connects, instead of writing it to the socket.

### Fixed

- **SMTP connection state after a failure.** A failed greeting, `EHLO`, `STARTTLS`,
TLS handshake, `AUTH`, recipient or message now closes the connection and
forgets the "authenticated" flag. Before, the socket stayed open, so the next
`send()` skipped `STARTTLS` and wrote `AUTH LOGIN` with the base64 credentials
in clear text. A greeting other than `220` is now an error.
- With `DSN` on, the `ORCPT` address is xtext-encoded (RFC 3461); before, a space
in an address (possible with `validate` off) could append SMTP parameters.
- `StreamSocketClient::enableCrypto()` refuses to start TLS while clear-text
bytes are still in the read buffer (STARTTLS response injection).
- The `Message-ID` domain is taken from the parsed sender, not from the raw
`fromEmail` option, and `Address::parse()` checks the whole input before the
display name is split off, so a CR, LF or NUL cannot hide in the part that is
discarded.
- A `<` or `>` inside an address is rejected (even with `validate` off): it could
close the SMTP path and add parameters (`RCPT TO:<a@x.com> NOTIFY=NEVER>`).
- `setHeader()`: a header the library writes itself for the message wins over a
custom one of the same name whatever the case (a custom `from`, or `bcc` next
to a real BCC list, is dropped instead of added as a second header). A header
the library does not write is kept as before: `setHeader('Cc'|'Bcc'|'To', …)`
without `setCC()`/`setBCC()`/`setTo()` still adds that header. (3.0.0 lost a
custom `To` on sendmail and SMTP when the message had no To recipient; it is now
kept there too. `sendmail -t` reads recipients from the headers, so such a
hand-set `To` is now also a recipient on sendmail.) A name with a space, a
colon or any non-printable or non-ASCII character throws a `MailerException`.
- `setAltMessage()` strips carriage returns like `setMessage()`. The SMTP
dot-stuffing now also handles a bare `"\r"` or `"\n\r"` newline.
- A `"` or `\` in an attachment name is escaped inside the quoted `name`
parameter; the generated Content-ID keeps only `[A-Za-z0-9._-]` of the name.
- `QEncoder`: input that is not valid UTF-8 is replaced with `?` instead of
raising iconv notices and producing garbage, and the fallback encoder for a
non-UTF-8 charset writes the missing `=` before each byte, so the encoded-words
are valid again.
- `HeaderRenderer` (used by all three transports) and the `mail()` / sendmail
transports refuse a header name that is not a field name, a value with a line
break other than a fold (a line break followed by a space or tab), and
recipients with a line break or angle bracket, so a `PreparedEmail` built by
hand cannot inject headers. A MIME boundary from `setBoundaryFactory()` that is
empty or contains a quote, CR, LF or NUL throws a `MailerException`.

## [3.0.0] - 2026-11-22

### Changed (breaking)
Expand Down
38 changes: 28 additions & 10 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,34 +23,42 @@ $mailer = Mailer::newInstance(['protocol' => 'smtp', /* … */]);
### `setFrom(string $from, string $name = '', ?string $returnPath = null): self`
Sets the sender. `$from` may be `address` or `"Name" <address>`; `$name` wins
over an embedded name. `$returnPath` sets the envelope sender.
**Throws** `InvalidAddressException`.
**Throws** `InvalidAddressException` — also when the address, the name or
`$returnPath` contains a CR, LF or NUL, whatever the `validate` option says.

### `setReplyTo(string $replyTo, string $name = ''): self`
Sets the `Reply-To`. Defaults to the sender when never called.
**Throws** `InvalidAddressException`.
**Throws** `InvalidAddressException` (also for a CR, LF or NUL, even with
`validate` off).

### `setTo(string|array $to): self`
Sets the To recipients. Accepts one address, a comma/space-separated string, or
an array. **Throws** `InvalidAddressException`.
an array. **Throws** `InvalidAddressException`. An address containing a CR, LF or
NUL is rejected even with `validate` off; in a string, whitespace (including line
breaks) still separates addresses.

### `setCC(string|array $cc): self`
Sets the CC recipients. **Throws** `InvalidAddressException`.
Sets the CC recipients. **Throws** `InvalidAddressException` (same line-break
rule as `setTo()`).

### `setBCC(string|array $bcc, ?int $limit = null): self`
Sets the BCC recipients. A non-null `$limit` enables [BCC batching](Sending-Mail.md#bcc-batching)
with that batch size. **Throws** `InvalidAddressException`.
with that batch size. **Throws** `InvalidAddressException` (same line-break rule as
`setTo()`).

## Content

### `setSubject(string $subject): self`
Sets the subject. Encoded (RFC 2047 Q) automatically when it contains non-ASCII.
CR, LF and NUL are removed when the message is built.

### `setMessage(string $body): self`
Sets the body (plain text or HTML depending on the mail type). Carriage returns
are stripped and surrounding blank lines trimmed.

### `setAltMessage(string $str): self`
Sets the plain-text alternative used for HTML messages.
Sets the plain-text alternative used for HTML messages. Carriage returns are
stripped, like in `setMessage()`.

### `setMailType(string $type = 'text'): self`
`'html'` for the value `html` (case-insensitive), otherwise `'text'`.
Expand All @@ -60,11 +68,13 @@ Sets the plain-text alternative used for HTML messages.
### `attach(string $file, string $disposition = '', ?string $newName = null, ?string $mime = null): self`
Attaches a file from disk. `$disposition` defaults to `attachment` (use `inline`
for embedded images), `$newName` overrides the displayed name, `$mime` skips
auto-detection. **Throws** `AttachmentException`.
auto-detection. **Throws** `AttachmentException`, also when the name, disposition
or MIME type contains a CR, LF or NUL.

### `attachContent(string $content, string $name, string $disposition = 'attachment', ?string $mime = null): self`
Attaches in-memory/generated content. `$mime` defaults to
`application/octet-stream`.
`application/octet-stream`. **Throws** `AttachmentException` when the name,
disposition or MIME type contains a CR, LF or NUL.

### `setAttachmentCID(string $fileName): string`
Promotes a previously added attachment (matched by its path/name) to an inline
Expand All @@ -74,8 +84,14 @@ Promotes a previously added attachment (matched by its path/name) to an inline
## Formatting & headers

### `setHeader(string $header, string $value): self`
Adds a custom header. CR/LF are stripped; library-managed headers take
precedence.
Adds a custom header. CR, LF and NUL are stripped from the value. A header the
library writes for the message itself (From, Subject, To with To recipients,
Cc with CC recipients,
Bcc with BCC recipients on sendmail and `mail()`, Date, Message-ID, …) wins over
a custom one of the same name, whatever the case; one it does not write is kept
as you set it. Use `setCC()`/`setBCC()` for recipients, not headers.
**Throws** `MailerException` when the header name is not printable ASCII
without `:` or spaces.

### `setPriority(int $n = 3): self`
`X-Priority`, 1 (highest)–5 (lowest); out-of-range → 3.
Expand Down Expand Up @@ -136,6 +152,8 @@ Overrides the protocol-derived transport (used in [Testing](Testing.md)).

### `setBoundaryFactory(callable $factory): self`
Overrides the MIME boundary generator: `callable(string $prefix): string`.
`send()` throws a `MailerException` for an empty boundary or one containing a
quote, CR, LF or NUL.

---

Expand Down
7 changes: 6 additions & 1 deletion docs/Attachments.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ $mailer->attach(
```

If the file cannot be read, or its type cannot be detected and you didn't supply
one, `attach()` throws [`AttachmentException`](Error-Handling.md).
one, `attach()` throws [`AttachmentException`](Error-Handling.md). It also throws
when the name, disposition or MIME type contains a CR, LF or NUL, since they are
written into the part's MIME headers (this applies to `attachContent()` too). A
`"` or `\` in the name is escaped with a backslash inside the quoted `name`
parameter, and the generated Content-ID keeps only letters, digits, `.`, `_` and
`-` of the name (anything else becomes `_`).

## In-memory or generated content

Expand Down
6 changes: 3 additions & 3 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ $mailer = Mailer::newInstance([
| `fromEmail` | string | `''` | Sender used when [`setFrom()`](Sending-Mail.md) is not called. |
| `fromName` | string | `''` | Display name paired with `fromEmail`. |
| `mailType` | string | `'text'` | `'text'` or `'html'`. |
| `charset` | string | `'UTF-8'` | Character set; stored upper-cased. |
| `charset` | string | `'UTF-8'` | Character set; stored upper-cased. A CR, LF or NUL throws a `ConfigurationException`. |
| `priority` | int | `3` | `X-Priority`, 1 (highest)–5 (lowest); out-of-range → 3. |
| `altMessage` | string | `''` | Plain-text alternative for HTML messages. |
| `userAgent` | string | `'InitPHP Mailer'` | `User-Agent` / `X-Mailer` header value. |
| `validate` | bool | `true` | Validate addresses as they are added. Turning it off also removes the CR/LF check — see [Error Handling](Error-Handling.md). |
| `userAgent` | string | `'InitPHP Mailer'` | `User-Agent` / `X-Mailer` header value. A CR, LF or NUL throws a `ConfigurationException`. |
| `validate` | bool | `true` | Validate addresses as they are added. Turning it off removes the format check only; a CR, LF, NUL, `<` or `>` in an address is rejected either way — see [Error Handling](Error-Handling.md). |

## Transport selection

Expand Down
15 changes: 12 additions & 3 deletions docs/Encoding-and-Headers.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ $mailer->setSubject('Café ☕');
```

Encoding happens when the message is built, so you always pass plain strings.
Line breaks and NUL are removed from a subject; a display name containing one is
rejected with an `InvalidAddressException`. With a `UTF-8` charset, bytes that are
not valid UTF-8 are replaced with `?` before encoding. With any other charset
the bytes are encoded as they are and must already be in that charset (the
mailer does not convert them).

## Body encoding

Expand Down Expand Up @@ -83,9 +88,13 @@ Out-of-range values fall back to 3.

## Custom headers

Add any header with `setHeader()`. CR/LF are stripped from the value to prevent
header injection, and the headers the library manages (From, To, Subject, Date,
Message-ID, MIME-Version, X-*, …) always take precedence over custom ones.
Add any header with `setHeader()`. CR, LF and NUL are stripped from the value to
prevent header injection, a header name that is not printable ASCII without `:`
or spaces throws a `MailerException`. The headers the library writes itself
(From, To, Subject, Date, Message-ID, MIME-Version, X-Mailer, …, and Cc/Bcc when
there are such recipients) win over a custom header of the same name, whatever
the case; a header the library does not write is kept. See
[Sending Mail](Sending-Mail.md#custom-headers).

```php
$mailer->setHeader('List-Unsubscribe', '<https://example.com/unsubscribe>');
Expand Down
31 changes: 14 additions & 17 deletions docs/Error-Handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ MailerException (extends \RuntimeException)

| Exception | Thrown when | Thrown by |
| --- | --- | --- |
| `InvalidAddressException` | An address fails validation (and validation is on). | `setFrom()`, `setReplyTo()`, `setTo()`, `setCC()`, `setBCC()` |
| `ConfigurationException` | A required value is missing: no sender, no recipient, empty SMTP host, auth without credentials. | `send()` |
| `AttachmentException` | A file can't be read, its type can't be detected, or `setAttachmentCID()` finds no match. | `attach()`, `setAttachmentCID()` |
| `InvalidAddressException` | An address fails validation (and validation is on), or an address or return path contains a CR, LF, NUL, `<` or `>`, or a display name a CR, LF or NUL (always). | `setFrom()`, `setReplyTo()`, `setTo()`, `setCC()`, `setBCC()`, `send()` |
| `ConfigurationException` | A required value is missing: no sender, no recipient, empty SMTP host, auth without credentials; or `userAgent`/`charset` contains a CR, LF or NUL. | `send()`, `new Mailer()` |
| `AttachmentException` | A file can't be read, its type can't be detected, the name, disposition or MIME type contains a CR, LF or NUL, or `setAttachmentCID()` finds no match. | `attach()`, `attachContent()`, `setAttachmentCID()` |
| `MailerException` (the base type) | A custom header name is not a valid field name; a MIME boundary from `setBoundaryFactory()` is empty or contains a quote, CR, LF or NUL; a header or subject handed to a transport by hand contains a line break other than a fold. | `setHeader()`, `send()` |
| `TransportException` | Delivery failed: refused connection, unexpected SMTP reply, sendmail non-zero exit, or `mail()` returning false. | `send()` |

## Catch everything
Expand Down Expand Up @@ -56,20 +57,16 @@ Need to accept addresses the PHP filter rejects? Turn validation off:
$mailer = Mailer::newInstance(['validate' => false]);
```

> **Security:** `validate => false` removes the only check on addresses. The
> mailer only trims whitespace from the ends of an address, so a CR or LF inside
> one (`user@example.com\r\nBcc: attacker@example.test`) is written into the
> `From` / `Cc` header or the SMTP command as given, which lets a request-supplied
> address add headers or recipients. If you turn validation off, reject line
> breaks yourself before the address reaches the mailer:
>
> ```php
> if (preg_match('/[\r\n]/', $address) === 1) {
> throw new \InvalidArgumentException('Invalid address.');
> }
> ```
>
> Never turn validation off for addresses that come from user input.
> **Security:** `validate => false` removes the format check on addresses, but
> not the character check. A CR, LF or NUL inside an address or a display name
> (`user@example.com\r\nBcc: attacker@example.test`), or a `<` or `>` inside an
> address (`user@example.com> NOTIFY=NEVER`), is rejected with an
> `InvalidAddressException` whether validation is on or off, so a request-supplied
> address cannot start another header or add parameters to an SMTP command. Only
> a leading or trailing line break is trimmed. The check does not limit how many
> recipients a string names: `"a@x.com,b@x.com"` is two. Avoid turning validation
> off for addresses that come from user input, and pass a single untrusted
> address as `setTo([$address])`.

## Handle delivery failures specifically

Expand Down
24 changes: 10 additions & 14 deletions docs/FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,20 +58,16 @@ rejects, disable validation:
$mailer = Mailer::newInstance(['validate' => false]);
```

> **Security:** `validate => false` removes the only check on addresses. The
> mailer only trims whitespace from the ends of an address, so a CR or LF inside
> one (`user@example.com\r\nBcc: attacker@example.test`) is written into the
> `From` / `Cc` header or the SMTP command as given, which lets a request-supplied
> address add headers or recipients. If you turn validation off, reject line
> breaks yourself before the address reaches the mailer:
>
> ```php
> if (preg_match('/[\r\n]/', $address) === 1) {
> throw new \InvalidArgumentException('Invalid address.');
> }
> ```
>
> Never turn validation off for addresses that come from user input.
> **Security:** `validate => false` removes the format check on addresses, but
> not the character check. A CR, LF or NUL inside an address or a display name
> (`user@example.com\r\nBcc: attacker@example.test`), or a `<` or `>` inside an
> address (`user@example.com> NOTIFY=NEVER`), is rejected with an
> `InvalidAddressException` whether validation is on or off, so a request-supplied
> address cannot start another header or add parameters to an SMTP command. Only
> a leading or trailing line break is trimmed. The check does not limit how many
> recipients a string names: `"a@x.com,b@x.com"` is two. Avoid turning validation
> off for addresses that come from user input, and pass a single untrusted
> address as `setTo([$address])`.

### Non-Latin subjects or names look like `=?UTF-8?Q?...?=`.

Expand Down
15 changes: 13 additions & 2 deletions docs/SMTP-Transport.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ With `'SMTPKeepAlive' => true` the connection is reused between messages — an
avoids the connect/handshake cost when sending many messages in a loop. The
connection is closed when the mailer is garbage-collected.

If a send fails at any point — the greeting or `EHLO` is refused, `STARTTLS` is
refused or the TLS handshake fails, authentication or a recipient is rejected,
or the message itself is rejected — the connection is closed and the
"authenticated" state is forgotten. The next `send()` opens a new connection and
starts again from the greeting, `STARTTLS` and `AUTH`, so credentials are never
sent over a connection that did not finish upgrading to TLS.

```php
$mailer = Mailer::newInstance([
'protocol' => 'smtp',
Expand All @@ -102,7 +109,9 @@ foreach ($recipients as $to) {
## Delivery Status Notifications (DSN)

`'DSN' => true` appends `NOTIFY=SUCCESS,DELAY,FAILURE` and an `ORCPT` to each
`RCPT TO`, asking the server for delivery notifications (if it supports DSN).
`RCPT TO`, asking the server for delivery notifications (if it supports DSN). The
address in `ORCPT` is encoded as RFC 3461 `xtext` (a space, `+`, `=` or any byte
outside `!`..`~` becomes `+XX`), so an address cannot add parameters.

## Timeouts

Expand All @@ -117,7 +126,9 @@ to socket reads/writes.
| Auth enabled but no username/password | `ConfigurationException` |
| Connection refused / cannot open socket | `TransportException` |
| Unexpected SMTP reply (e.g. `550`, `535`) | `TransportException` (code = reply code) |
| TLS negotiation fails | `TransportException` |
| The server's greeting is not `220` | `TransportException` (code = reply code) |
| TLS negotiation fails, or bytes arrived in clear text together with the `STARTTLS` reply | `TransportException` |
| A recipient contains a CR, LF, NUL, `<` or `>`, or the client hostname contains a CR, LF or NUL | `InvalidAddressException` / `TransportException`, before connecting |

```php
use InitPHP\Mailer\Exception\TransportException;
Expand Down
Loading
Loading