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