mailing_list.phps 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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, so 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 = mysql_connect('localhost', 'username', 'password');
  26. mysql_select_db('mydb', $mysql);
  27. $result = mysql_query("SELECT full_name, email, photo FROM mailinglist WHERE sent = false", $mysql);
  28. while ($row = mysql_fetch_array($result)) {
  29. $mail->addAddress($row['email'], $row['full_name']);
  30. $mail->addStringAttachment($row['photo'], 'YourPhoto.jpg'); //Assumes the image data is stored in the DB
  31. if (!$mail->send()) {
  32. echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
  33. break; //Abandon sending
  34. } else {
  35. echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("@", "&#64;", $row['email']) . ')<br />';
  36. //Mark it as sent in the DB
  37. mysql_query(
  38. "UPDATE mailinglist SET sent = true WHERE email = '" . mysql_real_escape_string($row['email'], $mysql) . "'"
  39. );
  40. }
  41. // Clear all addresses and attachments for next loop
  42. $mail->clearAddresses();
  43. $mail->clearAttachments();
  44. }