mailing_list.phps 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * This example shows how to send a message to a whole list of recipients efficiently.
  4. */
  5. //Import the PHPMailer class into the global namespace
  6. use PHPMailer\PHPMailer\PHPMailer;
  7. error_reporting(E_STRICT | E_ALL);
  8. date_default_timezone_set('Etc/UTC');
  9. require '../vendor/autoload.php';
  10. $mail = new PHPMailer;
  11. $body = file_get_contents('contents.html');
  12. $mail->isSMTP();
  13. $mail->Host = 'smtp.example.com';
  14. $mail->SMTPAuth = true;
  15. $mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
  16. $mail->Port = 25;
  17. $mail->Username = 'yourname@example.com';
  18. $mail->Password = 'yourpassword';
  19. $mail->setFrom('list@example.com', 'List manager');
  20. $mail->addReplyTo('list@example.com', 'List manager');
  21. $mail->Subject = "PHPMailer Simple database mailing list test";
  22. //Same body for all messages, so set this before the sending loop
  23. //If you generate a different body for each recipient (e.g. you're using a templating system),
  24. //set it inside the loop
  25. $mail->msgHTML($body);
  26. //msgHTML also sets AltBody, but if you want a custom one, set it afterwards
  27. $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
  28. //Connect to the database and select the recipients from your mailing list that have not yet been sent to
  29. //You'll need to alter this to match your database
  30. $mysql = mysqli_connect('localhost', 'username', 'password');
  31. mysqli_select_db($mysql, 'mydb');
  32. $result = mysqli_query($mysql, 'SELECT full_name, email, photo FROM mailinglist WHERE sent = false');
  33. foreach ($result as $row) {
  34. $mail->addAddress($row['email'], $row['full_name']);
  35. if (!empty($row['photo'])) {
  36. $mail->addStringAttachment($row['photo'], 'YourPhoto.jpg'); //Assumes the image data is stored in the DB
  37. }
  38. if (!$mail->send()) {
  39. echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
  40. break; //Abandon sending
  41. } else {
  42. echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("@", "&#64;", $row['email']) . ')<br />';
  43. //Mark it as sent in the DB
  44. mysqli_query(
  45. $mysql,
  46. "UPDATE mailinglist SET sent = true WHERE email = '" .
  47. mysqli_real_escape_string($mysql, $row['email']) . "'"
  48. );
  49. }
  50. // Clear all addresses and attachments for next loop
  51. $mail->clearAddresses();
  52. $mail->clearAttachments();
  53. }