mailing_list.phps 2.2 KB

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