<?php ini_set('max_execution_time', 3600);
/**
 * Created by PhpStorm.
 * User: Arslan
 * Date: 10/10/2018
 * Time: 1:21 PM
 */

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'mailer/Exception.php';
require 'mailer/PHPMailer.php';
require 'mailer/SMTP.php';

$contactDB = new mysqli("localhost","ipspkorg_contact","contactDB","ipspkorg_contacts");
if($contactDB->connect_error){
    die("Connection Failed: " . $contactDB->connect_error);
}

if($qry = $contactDB->query("SELECT id, name, email from mailer WHERE flag = 0 and list = 'CPEC'")) {
    if ($qry->num_rows > 0) {
        while ($row = $qry->fetch_assoc()) {

            $id = $row['id'];
            $email = $row['email'];
            $name = $row['name'];

            try {
                $mail = new PHPMailer(true);
                $mail->SMTPDebug = 2;
                $mail->IsSMTP();                                      // set mailer to use SMTP
                $mail->Host = "mail.ips.net.pk";  // specify main and backup server
                $mail->SMTPAuth = true;     // turn on SMTP authentication
                $mail->Username = "contact.cpecef@gmail.com";  // SMTP username
                $mail->Password = "muqarab1"; // SMTP password
                $mail->port = 26;

                $mail->From = "contact.cpecef@gmail.com";
                $mail->FromName = "";
                $mail->AddAddress($email, $name);

                $mail->addEmbeddedImage('invitations/cpec.jpg','cpec');

                $mail->addAttachment('invitations/cpec.jpg');

                $mail->WordWrap = 50;                                 // set word wrap to 50 characters
                $mail->IsHTML(true);                                  // set email format to HTML

                $mail->Subject = "[Invitation] CPEC FUTURE: Amidst Hybrid Security Challenges & Emerging Business Opportunities";
                $mail->Body = "<img src='cid:cpec' width='100%'/>";
                $mail->AltBody = "Please contact us.. Our Website address is www.ips.org.pk";

                $mail->Send();

                if($contactDB->query("UPDATE mailer set flag = 1 WHERE id = $id")) {
                    echo "Message has been sent";
                }

            }catch (Exception $e) {
                echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
            }
            sleep(5);
        }
    }
}