<?php
if (true): // turn on and off before use
$limit = 50; // limit of emails to send per 'session'
$table = 'foo'; // mysql table name
// connect to mysql database
/* ========================================================================================== */
$dbh = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// phpmailer class
/* ========================================================================================== */
require_once $_SERVER['DOCUMENT_ROOT'] . '/phpMailer_v2.2.1/class.phpmailer.php'; // http://phpmailer.worxware.com
$mail = new PHPMailer();
$body = file_get_contents('contents.html'); // file to send
$body = eregi_replace("[\]",'',$body); // escape
$mail->IsSMTP(); // enable smtp authentication
$mail->Host = "smtp.domain_name.com"; // host address
$mail->SMTPAuth = true; // authenticate
$mail->SMTPKeepAlive = true; // prevent close connection each email sent
$mail->Port = 587; // port number
$mail->Username = "email@address.com"; // username
$mail->Password = "password"; // password
$mail->From = 'email@address.com'; // from address
$mail->FromName = 'name and last name'; // from name
$mail->CharSet = "utf-8"; // character set
$mail->Subject = "Subject via smtp, basic with authentication"; // subject line
/* ========================================================================================== */
$stmt = $dbh->prepare("SELECT * FROM $table WHERE 1 AND date_sent != 'sent' AND date_sent != ' error' GROUP BY email");
$stmt->execute();
echo 'start time: ' . date(DATE_RSS) . "\n\n";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($i == $limit): exit(); endif; // exit if i = limit of emails
$i++;
$email = $row["email"]; // email address fetch from db
$mail->AddAddress($email);
$mail->MsgHTML($body); // set body for HTML mail
// $mail->Body = $body; // set body for plain text only
if ($mail->Send()):
$dbh->exec("UPDATE $table SET status = 'sent' WHERE email = '$email'"); // update status to sent
echo "sent to:" . "\t" . $row["email"] . "\t". date(DATE_RSS) . "\n"; // echo result
else:
$dbh->exec("UPDATE $table SET status = 'error' WHERE email = '$email'"); // update status to error ( better if cron job is running )
echo $mail->ErrorInfo . "\n"; // echo error if any
endif;
$mail->ClearAddresses(); // clear for next loop
} // end while
endif;
?>