Bonjour à tous,
J'ai modifié un script de newsletter (venant de https://codeshack.io/newsletter-system-php-mysql/). Le script fonctionne comme prévu, sauf que j'aimerais remplacer le php mail() par phpMailer.
Voici le code de ma page :
J'ai essayé avec ça :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 <?php include 'main.php'; // NOTICE: THE FOLLOWING PAGE IS UNRESTRICTED AND THEREFORE WE SUGGEST YOU IMPLEMENT RESTRICTIONS BEFORE GOING PRODUCTION // Get all subscribers from the database $stmt = $pdo->prepare('SELECT * FROM subscribers'); $stmt->execute(); $subscribers = $stmt->fetchAll(PDO::FETCH_ASSOC); // Process form if (isset($_POST['recipient'], $_POST['subject'], $_POST['template'])) { // From address $from = 'MMMontreal <info@mmmontreal.ca>'; // Email Headers $headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $from . "\r\n" . 'Return-Path: ' . $from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n"; // Determine the subscriber $subscriber = null; foreach ($subscribers as $s) { if ($s['email'] == $_POST['recipient']) { $subscriber = $s; } } // Make sure subscriber exists if ($subscriber) { // Update the unsubscribe link $unsubscribe_link = 'https://example.com/unsubscribe.php?email=' . $subscriber['email'] . '&code=' . sha1($subscriber['id'] . $subscriber['email']); // Replace the placeholder $template = str_replace('%unsubscribe_link%', $unsubscribe_link, $_POST['template']); // Send email to user if (mail($_POST['recipient'], $_POST['subject'], $template, $headers)) { exit('success'); } else { exit('Failed to send newsletter! Please check your SMTP mail server!'); } } else { exit('Invalid recipient!'); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,minimum-scale=1"> <title>Send Newsletter</title> <link href="style.css" rel="stylesheet" type="text/css"> <script src="js/tinymce.min.js" referrerpolicy="origin"></script> <script> function check_all() { var checkboxes = document.getElementsByClassName('recipient'); checkboxes = [...checkboxes]; for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = true } } function un_check_all() { var checkboxes = document.getElementsByClassName('recipient'); checkboxes = [...checkboxes]; for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = false; } } </script> </head> <body> <script> tinymce.init({ selector: 'textarea#template', height: 300, width:920, toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright alignjustify | indent outdent | wordcount | Template', setup: (editor) => { /* Menu items are recreated when the menu is closed and opened, so we need a variable to store the toggle menu item state. */ let toggleState = false; /* example, adding a toolbar menu button */ editor.ui.registry.addMenuButton('Template', { text: 'Template', fetch: (callback) => { const items = [ { type: 'menuitem', text: 'Template 1', onAction: () => editor.setContent(''), onAction: () => editor.insertContent('<em>You clicked menu item 1!</em>') }, { type: 'menuitem', text: 'Template 2', onAction: () => editor.setContent(''), onAction: () => editor.insertContent('<a href="www.google.ca">Google</a>') } ]; callback(items); } }); }, content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:16px }' }); </script> <form class="send-newsletter-form" method="post" action=""> <h1><i class="fa-regular fa-envelope"></i>Send Newsletter</h1> <div class="fields"> <label for="recipients">Recipients</label> <input type="button" name="Check_All" value="Select All" onClick="check_all()"> <input type="button" id="clearAll" value="Clear All" onClick="un_check_all();"> <div class="multi-select-list"> <?php foreach ($subscribers as $subscriber): ?> <label> <input type="checkbox" class="recipient" name="recipients[]" value="<?=$subscriber['email']?>"> <?=$subscriber['email']?> </label> <?php endforeach; ?> </div> <label for="subject">Subject</label> <div class="field"> <input type="text" id="subject" name="subject" placeholder="Subject" required> </div> <label for="template">Template</label> <div class="field"> <textarea id="template" name="template" placeholder="Enter your HTML template code here..." required></textarea> </div> <div class="responses"></div> </div> <input id="submit" type="submit" value="Send" onclick="tinyMCE.triggerSave(true,true);"> </form> <script> // Retrieve the form element const newsletterForm = document.querySelector('.send-newsletter-form'); // Declare variables let recipients = [], totalRecipients = 0, recipientsProcessed = 0; // Form submit event newsletterForm.onsubmit = event => { tinyMCE.triggerSave(true,true); event.preventDefault(); // Retrieve all recipients and delcare as an array recipients = [...document.querySelectorAll('.recipient:checked')]; // Total number of selected recipients totalRecipients = recipients.length; // Total number of recipients processed recipientsProcessed = 0; // Clear the responses (if any) document.querySelector('.responses').innerHTML = ''; // Temporarily disable the submit button document.querySelector('#submit').disabled = true; // Update the button value document.querySelector('#submit').value = `(1/${totalRecipients}) Processing...`; }; // The below code will send a new email every 3 seconds, but only if the form has been processed setInterval(() => { // If there are recipients... if (recipients.length > 0) { // Create form data let formData = new FormData(); // Append essential data formData.append('recipient', recipients[0].value); formData.append('template', document.querySelector('#template').value); formData.append('subject', document.querySelector('#subject').value); // Use AJAX to process the form fetch(newsletterForm.action, { method: 'POST', body: formData }).then(response => response.text()).then(data => { // If success if (data.includes('success')) { // Increment variables recipientsProcessed++; // Update button value document.querySelector('#submit').value = `(${recipientsProcessed}/${totalRecipients}) Processing...`; // When all recipients have been processed... if (recipientsProcessed == totalRecipients) { // Reset everything newsletterForm.reset(); document.querySelector('#submit').disabled = false; document.querySelector('#submit').value = `Submit`; document.querySelector('.responses').innerHTML = 'Newsletter sent successfully!'; } } else { // Error document.querySelector('.responses').innerHTML = data; } }); // Remove the first item from array recipients.shift(); } }, 3000); // 3000 ms = 3 seconds </script> </body> </html>
Sauf que la page m'indique que la newsletter à été envoyée, mais le "subscriber" (mon adresse courriel), ne reçoit rien.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 <?php include 'main.php'; // NOTICE: THE FOLLOWING PAGE IS UNRESTRICTED AND THEREFORE WE SUGGEST YOU IMPLEMENT RESTRICTIONS BEFORE GOING PRODUCTION // Get all subscribers from the database $stmt = $pdo->prepare('SELECT email FROM subscribers'); $stmt->execute(); $subscribers = $stmt->fetchAll(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,minimum-scale=1"> <title>Send Newsletter</title> <link href="style.css" rel="stylesheet" type="text/css"> <script src="js/tinymce.min.js" referrerpolicy="origin"></script> <script> function check_all() { var checkboxes = document.getElementsByClassName('recipient'); checkboxes = [...checkboxes]; for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = true } } function un_check_all() { var checkboxes = document.getElementsByClassName('recipient'); checkboxes = [...checkboxes]; for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = false; } } </script> </head> <body> <script> tinymce.init({ selector: 'textarea#template', height: 300, width:920, toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright alignjustify | indent outdent | wordcount | Template', setup: (editor) => { /* Menu items are recreated when the menu is closed and opened, so we need a variable to store the toggle menu item state. */ let toggleState = false; /* example, adding a toolbar menu button */ editor.ui.registry.addMenuButton('Template', { text: 'Template', fetch: (callback) => { const items = [ { type: 'menuitem', text: 'Template 1', onAction: () => editor.setContent(''), onAction: () => editor.insertContent('<em>You clicked menu item 1!</em>') }, { type: 'menuitem', text: 'Template 2', onAction: () => editor.setContent(''), onAction: () => editor.insertContent('<a href="www.google.ca">Google</a>') } ]; callback(items); } }); }, content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:16px }' }); </script> <form class="send-newsletter-form" method="post" action=""> <h1><i class="fa-regular fa-envelope"></i>Send Newsletter</h1> <div class="fields"> <label for="recipients">Recipients</label> <input type="button" name="Check_All" value="Select All" onClick="check_all()"> <input type="button" id="clearAll" value="Clear All" onClick="un_check_all();"> <div class="multi-select-list"> <?php foreach ($subscribers as $subscriber): ?> <label> <input type="checkbox" class="recipient" name="recipients[]" value="<?=$subscriber['email']?>"> <?=$subscriber['email']?> </label> <?php endforeach; ?> </div> <label for="subject">Subject</label> <div class="field"> <input type="text" id="subject" name="subject" placeholder="Subject" required> </div> <label for="template">Template</label> <div class="field"> <textarea id="template" name="template" placeholder="Enter your HTML template code here..." required></textarea> </div> <div class="responses"></div> </div> <input id="submit" type="submit" value="Send" onclick="tinyMCE.triggerSave(true,true);"> </form> <script> // Retrieve the form element const newsletterForm = document.querySelector('.send-newsletter-form'); // Declare variables let recipients = [], totalRecipients = 0, recipientsProcessed = 0; // Form submit event newsletterForm.onsubmit = event => { tinyMCE.triggerSave(true,true); event.preventDefault(); // Retrieve all recipients and delcare as an array recipients = [...document.querySelectorAll('.recipient:checked')]; // Total number of selected recipients totalRecipients = recipients.length; // Total number of recipients processed recipientsProcessed = 0; // Clear the responses (if any) document.querySelector('.responses').innerHTML = ''; // Temporarily disable the submit button document.querySelector('#submit').disabled = true; // Update the button value document.querySelector('#submit').value = `(1/${totalRecipients}) Processing...`; }; // The below code will send a new email every 3 seconds, but only if the form has been processed setInterval(() => { // If there are recipients... if (recipients.length > 0) { // Create form data let formData = new FormData(); // Append essential data formData.append('recipient', recipients[0].value); formData.append('template', document.querySelector('#template').value); formData.append('subject', document.querySelector('#subject').value); // Use AJAX to process the form fetch(newsletterForm.action, { method: 'POST', body: formData }).then(response => response.text()).then(data => { // If success if (data.includes('success')) { // Increment variables recipientsProcessed++; // Update button value document.querySelector('#submit').value = `(${recipientsProcessed}/${totalRecipients}) Processing...`; // When all recipients have been processed... if (recipientsProcessed == totalRecipients) { // Reset everything newsletterForm.reset(); document.querySelector('#submit').disabled = false; document.querySelector('#submit').value = `Submit`; document.querySelector('.responses').innerHTML = 'Newsletter sent successfully!'; } } else { // Error document.querySelector('.responses').innerHTML = data; } }); // Remove the first item from array recipients.shift(); } }, 3000); // 3000 ms = 3 seconds </script> </body> </html> <?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; require 'src/PHPMailer.php'; require 'src/SMTP.php'; if(isset($_POST['Submit'])) { foreach ($subscribers as $s) { if ($s['email'] == $_POST['recipient']) { $message = $_POST['template']; $fromsubject = $_POST['subject']; $subscribers = $_POST['recipient']; $unsubscribe_link = 'http://mmmontreal.ca/unsubscribe.php?email=' . $subscriber['email'] . '&code=' . sha1($subscriber['id'] . $subscriber['email']); $body = '<html><body>'; $body .= $fromsubject; $body .= $unsubscribe_link; $body .= '</body></html>'; $mail = new PHPMailer(True); $mail->CharSet = 'UTF-8'; $mail->isSMTP(); // Paramétrer le Mailer pour utiliser SMTP $mail->Host = 'mail.mmmontreal.ca'; // Spécifier le serveur SMTP $mail->SMTPAuth = true; // Activer authentication SMTP $mail->Username = 'smtp@mmmontreal.ca'; // Votre adresse email d'envoi $mail->Password = 'mMm0ntr&@l-2025'; // Le mot de passe de cette adresse email $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Accepter SSL $mail->Port = 465; $mail->setFrom('form@mmmontreal.ca', 'Contact form'); // Personnaliser l'envoyeur $mail->addAddress($subscribers); // Ajouter le destinataire $mail->addReplyTo('info@mmmontreal.ca', 'Information'); // L'adresse de réponse $mail->isHTML(true); // Paramétrer le format des emails en HTML ou non $mail->Subject = $fromsubject; $mail->Body = $body; if(!$mail->send()) { ?> <script> alert("Erreur");</script> <?php } else { ?> <script> alert("<?= __('formSend')?> ");</script> <?php } } } }?>
Est-ce que quelqu'un pourrait m'aider ?
Merci
Partager