Class: Attachment Mailer

Cette classe peut être utilisé pour composer et envoyer des messages avec de multiples fichiers attachés.

Améliorations Principales

  • Sécurité renforcée : Remplacement de md5(time()) par random_bytes() cryptographiquement sécurisé
  • Typage strict : Propriétés et paramètres typés pour prévenir les erreurs
  • Gestion d'erreurs : Exceptions au lieu de retours silencieux de false
  • Performance : RecursiveIteratorIterator au lieu de récursion manuelle
  • Standards modernes : Namespaces, PSR-12, constructor promotion
  • Maintenabilité : Code auto-documenté, méthodes chainables, enum pour types MIME

Recommandations

  1. Tests unitaires : Ajoutez des tests avec PHPUnit pour garantir le bon fonctionnement
  2. Bibliothèque email moderne : Considérez PHPMailer ou Symfony Mailer pour plus de fonctionnalités
  3. Configuration externalisée : Déplacez les headers par défaut dans un fichier de config
  4. Logging : Ajoutez un système de logs pour tracer les envois d'emails
  5. Queue système : Pour les volumes élevés, utilisez une queue (Redis, RabbitMQ)



Information sur les mises à jour

Dernière mise à jour :

15 Fév 2026
refactoring du code en PHP 8

8 470  vues
Compatibilité du code
PHP 8
  code classé dans   Classes
  code source classé dans   Classes
 
01
02
03
04
05
06
07
08
09
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
                    
<?php
/*------------------------------*/
/*
Titre : Class: Attachment Mailer

Auteur : freemh
Date édition : 19 Juil 2008
Date mise a jour : 15 Fev 2026

Rapport de la maj:
- refactoring du code en PHP 8
*/
/*------------------------------*/

declare(strict_types=1);

/**
* Modern PHP 8 Email Mailer with MIME Attachments
*
* Features:
* - PHP 8.3+ typed properties and constructor promotion
* - Proper exception handling
* - PSR-12 coding standards
* - Enum for content types
* - Return type declarations
* - Null safety with union types
*/

namespace App\Mail;

use RuntimeException;
use InvalidArgumentException;

enum ContentType: string
{
case TEXT_HTML = 'text/html';
case TEXT_PLAIN = 'text/plain';
case APPLICATION_OCTET_STREAM = 'application/octet-stream';
case APPLICATION_PDF = 'application/pdf';
case IMAGE_JPEG = 'image/jpeg';
case IMAGE_PNG = 'image/png';
}

class Mailer
{
private readonly string $mimeBoundary;
private string $emailMessage = '';
private array $attachments = [];

/**
* Constructor with promoted properties (PHP 8.0+)
*/
public function __construct(
private string $emailTo,
private string $emailSubject,
string $message,
private string $headers = '',
private string $charset = 'UTF-8'
) {
$this->validateEmail($emailTo);
$this->mimeBoundary = '==Multipart_Boundary_' . bin2hex(random_bytes(16)
) . '==';
$this->initializeHeaders();
$this->initializeMessage($message);
}

/**
* Validate email address
*/
private function validateEmail(string $email): void
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email address: {$email}"
);
}
}

/**
* Initialize MIME headers
*/
private function initializeHeaders(): void
{
$this->headers .= "\nMIME-Version: 1.0\n";
$this->headers .= "Content-Type: multipart/mixed;\n";
$this->headers .= " boundary=\"{$this->mimeBoundary}\"";
}

/**
* Initialize base email message
*/
private function initializeMessage(string $message): void
{
$this->emailMessage = "This is a multi-part message in MIME format.\n\n"
;
$this->emailMessage .= "--{$this->mimeBoundary}\n";
$this->emailMessage .=
"Content-Type: text/html; charset=\"{$this->charset}\"\n";
$this->emailMessage .= "Content-Transfer-Encoding: 7bit\n\n";
$this->emailMessage .= $message . "\n\n";
}

/**
* Add attachment from content
*/
public function attach(
string|ContentType $contentType,
string $filename,
string $content
): self {
$type = $contentType instanceof ContentType
? $contentType->value
: $contentType;

$encodedContent = chunk_split(base64_encode($content));

$this->emailMessage .= "--{$this->mimeBoundary}\n";
$this->emailMessage .= "Content-Type: {$type};\n";
$this->emailMessage .= " name=\"{$filename}\"\n";
$this->emailMessage .= "Content-Transfer-Encoding: base64\n\n";
$this->emailMessage .= $encodedContent . "\n\n";
$this->emailMessage .= "--{$this->mimeBoundary}\n";

$this->attachments[] = $filename;

return $this;
}

/**
* Attach a file from filesystem
*
* @throws RuntimeException if file cannot be read
*/
public function attachFile(string $filepath): self
{
if (!is_file($filepath) || !is_readable($filepath)) {
throw new RuntimeException(
"File not found or not readable: {$filepath}");
}

$content = file_get_contents($filepath);
if ($content === false) {
throw new RuntimeException("Failed to read file: {$filepath}");
}

$filename = basename($filepath);
$mimeType = mime_content_type($filepath) ?: ContentType::
APPLICATION_OCTET_STREAM->value;

return $this->attach($mimeType, $filename, $content);
}

/**
* Attach all files from a directory (recursive)
*
* @throws RuntimeException if directory cannot be read
*/
public function attachDirectory(string $directory): self
{
if (!is_dir($directory) || !is_readable($directory)) {
throw new RuntimeException(
"Directory not found or not readable: {$directory}");
}

$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator(
$directory,
\RecursiveDirectoryIterator::SKIP_DOTS
)
);

foreach ($iterator as $file) {
if ($file->isFile()) {
$this->attachFile($file->getPathname());
}
}

return $this;
}

/**
* Send email using PHP's mail() function
*
* @throws RuntimeException if mail sending fails
*/
public function send(): bool
{
$result = mail(
$this->emailTo,
$this->emailSubject,
$this->emailMessage,
$this->headers
);

if (!$result) {
throw new RuntimeException(
"Failed to send email to: {$this->emailTo}");
}

return $result;
}

/**
* Send email using IMAP
*
* @throws RuntimeException if IMAP extension is not loaded or sending fails
*/
public function sendViaImap(): bool
{
if (!extension_loaded('imap')) {
throw new RuntimeException("IMAP extension is not loaded");
}

$result = imap_mail(
$this->emailTo,
$this->emailSubject,
$this->emailMessage,
$this->headers
);

if (!$result) {
throw new RuntimeException(
"Failed to send email via IMAP to: {$this->emailTo}");
}

return $result;
}

/**
* Get email recipient
*/
public function getRecipient(): string
{
return $this->emailTo;
}

/**
* Get email subject
*/
public function getSubject(): string
{
return $this->emailSubject;
}

/**
* Get list of attached files
*
* @return array<string>
*/
public function getAttachments(): array
{
return $this->attachments;
}

/**
* Get attachment count
*/
public function getAttachmentCount(): int
{
return count($this->attachments);
}
}
?>
<?php
/*------------------------------*/
/*
Titre : Class: Attachment Mailer

Auteur : freemh
Date édition : 19 Juil 2008
Date mise a jour : 15 Fev 2026

Rapport de la maj:
- refactoring du code en PHP 8
*/
/*------------------------------*/

declare(strict_types=1);

/**
* Modern PHP 8 Email Mailer with MIME Attachments
*
* Features:
* - PHP 8.3+ typed properties and constructor promotion
* - Proper exception handling
* - PSR-12 coding standards
* - Enum for content types
* - Return type declarations
* - Null safety with union types
*/

namespace App\Mail;

use RuntimeException;
use InvalidArgumentException;

enum ContentType: string
{
case TEXT_HTML = 'text/html';
case TEXT_PLAIN = 'text/plain';
case APPLICATION_OCTET_STREAM = 'application/octet-stream';
case APPLICATION_PDF = 'application/pdf';
case IMAGE_JPEG = 'image/jpeg';
case IMAGE_PNG = 'image/png';
}

class Mailer
{
private readonly string $mimeBoundary;
private string $emailMessage = '';
private array $attachments = [];

/**
* Constructor with promoted properties (PHP 8.0+)
*/
public function __construct(
private string $emailTo,
private string $emailSubject,
string $message,
private string $headers = '',
private string $charset = 'UTF-8'
) {
$this->validateEmail($emailTo);
$this->mimeBoundary = '==Multipart_Boundary_' . bin2hex(random_bytes(16)
) . '==';
$this->initializeHeaders();
$this->initializeMessage($message);
}

/**
* Validate email address
*/
private function validateEmail(string $email): void
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException("Invalid email address: {$email}"
);
}
}

/**
* Initialize MIME headers
*/
private function initializeHeaders(): void
{
$this->headers .= "\nMIME-Version: 1.0\n";
$this->headers .= "Content-Type: multipart/mixed;\n";
$this->headers .= " boundary=\"{$this->mimeBoundary}\"";
}

/**
* Initialize base email message
*/
private function initializeMessage(string $message): void
{
$this->emailMessage = "This is a multi-part message in MIME format.\n\n"
;
$this->emailMessage .= "--{$this->mimeBoundary}\n";
$this->emailMessage .=
"Content-Type: text/html; charset=\"{$this->charset}\"\n";
$this->emailMessage .= "Content-Transfer-Encoding: 7bit\n\n";
$this->emailMessage .= $message . "\n\n";
}

/**
* Add attachment from content
*/
public function attach(
string|ContentType $contentType,
string $filename,
string $content
): self {
$type = $contentType instanceof ContentType
? $contentType->value
: $contentType;

$encodedContent = chunk_split(base64_encode($content));

$this->emailMessage .= "--{$this->mimeBoundary}\n";
$this->emailMessage .= "Content-Type: {$type};\n";
$this->emailMessage .= " name=\"{$filename}\"\n";
$this->emailMessage .= "Content-Transfer-Encoding: base64\n\n";
$this->emailMessage .= $encodedContent . "\n\n";
$this->emailMessage .= "--{$this->mimeBoundary}\n";

$this->attachments[] = $filename;

return $this;
}

/**
* Attach a file from filesystem
*
* @throws RuntimeException if file cannot be read
*/
public function attachFile(string $filepath): self
{
if (!is_file($filepath) || !is_readable($filepath)) {
throw new RuntimeException(
"File not found or not readable: {$filepath}");
}

$content = file_get_contents($filepath);
if ($content === false) {
throw new RuntimeException("Failed to read file: {$filepath}");
}

$filename = basename($filepath);
$mimeType = mime_content_type($filepath) ?: ContentType::
APPLICATION_OCTET_STREAM->value;

return $this->attach($mimeType, $filename, $content);
}

/**
* Attach all files from a directory (recursive)
*
* @throws RuntimeException if directory cannot be read
*/
public function attachDirectory(string $directory): self
{
if (!is_dir($directory) || !is_readable($directory)) {
throw new RuntimeException(
"Directory not found or not readable: {$directory}");
}

$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator(
$directory,
\RecursiveDirectoryIterator::SKIP_DOTS
)
);

foreach ($iterator as $file) {
if ($file->isFile()) {
$this->attachFile($file->getPathname());
}
}

return $this;
}

/**
* Send email using PHP's mail() function
*
* @throws RuntimeException if mail sending fails
*/
public function send(): bool
{
$result = mail(
$this->emailTo,
$this->emailSubject,
$this->emailMessage,
$this->headers
);

if (!$result) {
throw new RuntimeException(
"Failed to send email to: {$this->emailTo}");
}

return $result;
}

/**
* Send email using IMAP
*
* @throws RuntimeException if IMAP extension is not loaded or sending fails
*/
public function sendViaImap(): bool
{
if (!extension_loaded('imap')) {
throw new RuntimeException("IMAP extension is not loaded");
}

$result = imap_mail(
$this->emailTo,
$this->emailSubject,
$this->emailMessage,
$this->headers
);

if (!$result) {
throw new RuntimeException(
"Failed to send email via IMAP to: {$this->emailTo}");
}

return $result;
}

/**
* Get email recipient
*/
public function getRecipient(): string
{
return $this->emailTo;
}

/**
* Get email subject
*/
public function getSubject(): string
{
return $this->emailSubject;
}

/**
* Get list of attached files
*
* @return array<string>
*/
public function getAttachments(): array
{
return $this->attachments;
}

/**
* Get attachment count
*/
public function getAttachmentCount(): int
{
return count($this->attachments);
}
}
?>

Exemple :

 
01
02
03
04
05
06
07
08
09
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
                    
<?php

declare(strict_types=1);

require_once 'Mailer.php';

use App\Mail\Mailer;
use App\Mail\ContentType;

// Example 1: Simple HTML email
try {
$mailer = new Mailer(
emailTo: 'recipient@example.com',
emailSubject: 'Welcome to Our Service',
message: '<h1>Welcome!</h1><p>Thank you for joining us.</p>',
headers: 'From: sender@example.com'
);

$mailer->send();
echo "Email sent successfully!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

// Example 2: Email with file attachment
try {
$mailer = new Mailer(
emailTo: 'client@example.com',
emailSubject: 'Your Invoice',
message: '<p>Please find your invoice attached.</p>',
headers: 'From: billing@example.com'
);

// Attach a file from filesystem
$mailer->attachFile('/path/to/invoice.pdf');

$mailer->send();
echo "Email with attachment sent!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

// Example 3: Email with multiple attachments using method chaining
try {
$mailer = new Mailer(
emailTo: 'team@example.com',
emailSubject: 'Monthly Reports',
message: '<p>Here are all the reports for this month.</p>',
headers: 'From: reports@example.com'
);

// Method chaining for multiple attachments
$mailer
->attachFile('/path/to/report1.pdf')
->attachFile('/path/to/report2.pdf')
->attachFile('/path/to/chart.png')
->send();

echo "Email with {$mailer->getAttachmentCount()} attachments sent!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

// Example 4: Attach content directly (without file)
try {
$mailer = new Mailer(
emailTo: 'admin@example.com',
emailSubject: 'System Log',
message: '<p>System log attached.</p>',
headers: 'From: system@example.com'
);

// Create content on-the-fly
$logContent = "Application log:\n" . date('Y-m-d H:i:s') .
" - System started\n";

$mailer->attach(
contentType: ContentType::TEXT_PLAIN,
filename: 'system.log',
content: $logContent
);

$mailer->send();
echo "Email with generated content sent!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

// Example 5: Attach all files from a directory
try {
$mailer = new Mailer(
emailTo: 'backup@example.com',
emailSubject: 'Backup Files',
message: '<p>All backup files from the directory.</p>',
headers: 'From: backup@example.com'
);

// Attach entire directory (recursive)
$mailer->attachDirectory('/path/to/backup/folder');

$mailer->send();
echo "Backup email sent with all files!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
<?php

declare(strict_types=1);

require_once 'Mailer.php';

use App\Mail\Mailer;
use App\Mail\ContentType;

// Example 1: Simple HTML email
try {
$mailer = new Mailer(
emailTo: 'recipient@example.com',
emailSubject: 'Welcome to Our Service',
message: '<h1>Welcome!</h1><p>Thank you for joining us.</p>',
headers: 'From: sender@example.com'
);

$mailer->send();
echo "Email sent successfully!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

// Example 2: Email with file attachment
try {
$mailer = new Mailer(
emailTo: 'client@example.com',
emailSubject: 'Your Invoice',
message: '<p>Please find your invoice attached.</p>',
headers: 'From: billing@example.com'
);

// Attach a file from filesystem
$mailer->attachFile('/path/to/invoice.pdf');

$mailer->send();
echo "Email with attachment sent!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

// Example 3: Email with multiple attachments using method chaining
try {
$mailer = new Mailer(
emailTo: 'team@example.com',
emailSubject: 'Monthly Reports',
message: '<p>Here are all the reports for this month.</p>',
headers: 'From: reports@example.com'
);

// Method chaining for multiple attachments
$mailer
->attachFile('/path/to/report1.pdf')
->attachFile('/path/to/report2.pdf')
->attachFile('/path/to/chart.png')
->send();

echo "Email with {$mailer->getAttachmentCount()} attachments sent!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

// Example 4: Attach content directly (without file)
try {
$mailer = new Mailer(
emailTo: 'admin@example.com',
emailSubject: 'System Log',
message: '<p>System log attached.</p>',
headers: 'From: system@example.com'
);

// Create content on-the-fly
$logContent = "Application log:\n" . date('Y-m-d H:i:s') .
" - System started\n";

$mailer->attach(
contentType: ContentType::TEXT_PLAIN,
filename: 'system.log',
content: $logContent
);

$mailer->send();
echo "Email with generated content sent!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

// Example 5: Attach all files from a directory
try {
$mailer = new Mailer(
emailTo: 'backup@example.com',
emailSubject: 'Backup Files',
message: '<p>All backup files from the directory.</p>',
headers: 'From: backup@example.com'
);

// Attach entire directory (recursive)
$mailer->attachDirectory('/path/to/backup/folder');

$mailer->send();
echo "Backup email sent with all files!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>

      Fonctions du code - Doc officielle PHP

   php.net  
Description
Versions PHP
    array
Crée un tableau
PHP 4, 5, 7 et 8
    base64_encode
Encode une chaîne en MIME base64
PHP 4, 5, 7 et 8
    basename
Retourne le nom de la composante finale d'un chemin
PHP 4, 5, 7 et 8
    bin2hex
Convertit des données binaires en représentation hexadécimale
PHP 4, 5, 7 et 8
    chunk_split
Scinde une chaîne
PHP 4, 5, 7 et 8
    count
Compte tous les éléments d'un tableau ou dans un objet Countable
PHP 4, 5, 7 et 8
    date
Formate un horodatage Unix
PHP 4, 5, 7 et 8
    echo
Affiche une chaîne de caractères
PHP 4, 5, 7 et 8
    extension_loaded
Détermine si une extension est chargée ou non
PHP 4, 5, 7 et 8
    file_get_contents
Lit tout un fichier dans une chaîne
PHP 4, 5, 7 et 8
    filter_var
Filtre une variable avec un filtre spécifique
PHP 4, 5, 7 et 8
    imap_mail
Envoie un message mail
PHP 4, 5, 7 et 8
    is_dir
Indique si le fichier est un dossier
PHP 4, 5, 7 et 8
    is_file
Indique si le fichier est un véritable fichier
PHP 4, 5, 7 et 8
    is_readable
Indique si un fichier existe et est accessible en lecture
PHP 4, 5, 7 et 8
    mail
Envoi de mail
PHP 4, 5, 7 et 8
    mime_content_type
Détecte le type de contenu d'un fichier
PHP 4, 5, 7 et 8
    return
Retourne le controle du programme au module appelant
PHP 4, 5, 7 et 8
Minimum 10 mots. Votre commentaire sera visible après validation.


 Autres snippets qui pourraient vous intéresser

ICQ class - PHP Sources

Compatibilité : PHP 4, PHP 5

Classe ICQ simple pour vérifié si un utilisateur est en ligne ou non.

Class INIT - PHP Sources

Compatibilité : PHP 7

La class INIT permet d'initialisé tout site Web. Il sécurise les données envoyées par l'utilisateur (GET, POST, FILE etc.).

* Requêtes exécutées avec Recherche Contextuelle

  Les derniers scripts

PHP 8.5.5

logo PHP
Langue langue us
Date 12 Avril
Taille 32 Mo
Catégorie PHP

PHP 8.4.20

logo PHP
Langue langue us
Date 12 Avril
Taille 30 Mo
Catégorie PHP

Serendipity 2.6.0

logo Serendipity
Langue langue fr
Date 11 Avril
Taille 15 Mo
Catégorie Blogs

Drupal 11.3.6

logo Drupal
Langue langue us
Date 11 Avril
Taille 34 Mo
Catégorie CMS

TYPO3 14.2.0

logo TYPO3
Langue langue fr
Date 10 Avril
Taille 38 Mo
Catégorie CMS

Dolibarr ERP 23.0.1

logo Dolibarr ERP
Langue langue fr
Date 09 Avril
Taille 89 Mo
Catégorie Logiciels
avatar

Freemh

  19 Juil 2008

  SOURCE   Télécharger

Information sur les mises à jour

Dernière mise à jour :

15 Fév 2026
refactoring du code en PHP 8

8 470 Vues
Compatibilité du code
PHP 8