IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

PHP & Base de données Discussion :

Newsletter avec phpMailer


Sujet :

PHP & Base de données

  1. #1
    Membre averti
    Homme Profil pro
    QA
    Inscrit en
    Septembre 2022
    Messages
    39
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Canada

    Informations professionnelles :
    Activité : QA

    Informations forums :
    Inscription : Septembre 2022
    Messages : 39
    Par défaut Newsletter avec phpMailer
    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 :
    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>
    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
    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
     
    	}
    	}
    }
    	}?>
    Sauf que la page m'indique que la newsletter à été envoyée, mais le "subscriber" (mon adresse courriel), ne reçoit rien.


    Est-ce que quelqu'un pourrait m'aider ?

    Merci

  2. #2
    Membre chevronné
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2022
    Messages
    307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 21
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2022
    Messages : 307
    Par défaut
    Bonjour,
    Un petit echo des datas passé dans ton mail stp ?
    Cdt
    Un problème sans solution est un problème mal posé. (Albert Einstein)

  3. #3
    Membre averti
    Homme Profil pro
    QA
    Inscrit en
    Septembre 2022
    Messages
    39
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Canada

    Informations professionnelles :
    Activité : QA

    Informations forums :
    Inscription : Septembre 2022
    Messages : 39
    Par défaut
    Voici le code fonctionnel

    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
    <?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 ($_SERVER["REQUEST_METHOD"] == "POST") {
        $message = $_POST['template']; // Corrected variable
        $fromsubject = $_POST['subject'];
     
        foreach ($subscribers as $s) {
            if ($s['email'] == $_POST['recipient']) {        
                $unsubscribe_link = 'http://mmmontreal.ca/unsubscribe.php?email=' . urlencode($s['email']);
     
                $body = '<html><body>';           
                $body .= nl2br(htmlspecialchars($message));
                $body .= '<p><a href="' . $unsubscribe_link . '">Unsubscribe</a></p>';
                $body .= '</body></html>';
     
                $mail = new PHPMailer(true);
                $mail->CharSet = 'UTF-8';
     
                $mail->isSMTP();
                $mail->Host = 'mail.mmmontreal.ca';
                $mail->SMTPAuth = true;
                $mail->Username = 'smtp@mmmontreal.ca';
                $mail->Password = <<smtp password >>;
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                $mail->Port = 465;
     
                $mail->setFrom('info@mmmontreal.ca', 'Newsletter');
                $mail->addAddress($s['email']);
                $mail->addReplyTo('info@mmmontreal.ca', 'Information');
     
                $mail->isHTML(true);
                $mail->Subject = $fromsubject;
                $mail->Body = $body;
     
                if(!$mail->send()) {
                    echo "<script>alert('Mail Error: " . $mail->ErrorInfo . "');</script>";
                } else {
     
                    echo "<script>alert('Newsletter sent successfully!');</script>";
                }
            }
        }
    }?>

  4. #4
    Modérateur
    Avatar de escartefigue
    Homme Profil pro
    bourreau
    Inscrit en
    Mars 2010
    Messages
    10 588
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Loir et Cher (Centre)

    Informations professionnelles :
    Activité : bourreau
    Secteur : Finance

    Informations forums :
    Inscription : Mars 2010
    Messages : 10 588
    Billets dans le blog
    10
    Par défaut
    La requête SELECT ne comporte aucune restriction WHERE , voulez vous vraiment lire toute la table "subscribers" ?
    Même s'il s'agit d'un envoi en masse, il y a peut être des "subscribers" inactifs, fermés ou autres, à qui il ne faut rien envoyer...

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. optimisation envoi newsletter avec phpmailer
    Par p_m_g dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 4
    Dernier message: 27/05/2009, 12h56
  2. [PHPMailer] Pb avec PHPMAILER et SENDMAIL
    Par sabine2000 dans le forum Bibliothèques et frameworks
    Réponses: 4
    Dernier message: 06/02/2007, 10h37
  3. [Mail] PHP et envoi d'email avec PHPmailer
    Par dolf13 dans le forum Langage
    Réponses: 6
    Dernier message: 14/07/2006, 00h51
  4. [Mail] Problème d'encodage avec phpmailer
    Par catmary dans le forum Langage
    Réponses: 8
    Dernier message: 29/06/2006, 10h56
  5. [FPDF] Créer un PDF et l'envoyer par email avec PHPMailer
    Par nico33307 dans le forum Bibliothèques et frameworks
    Réponses: 5
    Dernier message: 12/12/2005, 22h49

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo