Question

Please excuse my 'newbieness', this is my very first project in php. I am sure this is a very simple problem ... hopefully some easy points for someone!

I am trying to get an array from my database, run the Swift_Plugins_DecoratorPlugin and create a series of personalised messages to spool.

The problem is, the script works with a static array of data, but when I try to introduce live data from the database I am lost. I don't know how to create an array from the database to fit in the right way.

If anyone can help I would be very grateful for that!

What I have so far:

<?php

    $dbc = mysqli_connect('localhost', 'root', '', 'apptwo');
    $query = "SELECT id, username, email FROM users WHERE status=1";
    $result = mysqli_query($dbc, $query);
      $users = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $users[$row['email']] = $row['email'];
        $users[$row['username']] = $row['username'];
        $users[$row['id']] = $row['id'];
    }

    // Create the replacements array
    $replacements = array();
    foreach ($users as $user) {
      $replacements[$user["id"]] = array (
        "{fullname}" => $user["username"],
        "{transactions}" => $user["email"]
      );
    }

    $spool = new Swift_FileSpool(__DIR__."/spool");
    // Setup the transport and mailer
    $transport = Swift_SpoolTransport::newInstance($spool);

    // Create an instance of the plugin and register it
    $plugin = new Swift_Plugins_DecoratorPlugin($replacements);
    $mailer = Swift_Mailer::newInstance($transport);
    $mailer->registerPlugin($plugin);

    // Create the message
    $message = Swift_Message::newInstance();
    $message->setSubject("This email is sent using Swift Mailer");
    $message->setBody("You {fullname}, are our best client ever thanks " .
        " to the {transactions} transactions you made with us.");
    $message->setFrom("mailout@exampleco.com", "exampleco");

    // Send the email
    foreach($users as $user) {
      $message->setTo($user["email"], $user["fullname"]);
      $result = $mailer->send($message);
    }
    echo "SPOOLED $result emails";
    ?>

Working version with static data in array:

<?php

$users = array(
  array(
    "fullname" => "name",
    "operations" => 100,
    "email" => "name@name.com"
  ),
  array(
    "fullname" => "name2",
    "operations" => 50,
    "email" => "name2@name.com"
  )
);

// Create the replacements array
$replacements = array();
foreach ($users as $user) {
  $replacements[$user["email"]] = array (
    "{fullname}" => $user["fullname"],
    "{transactions}" => $user["operations"]
  );
}

$spool = new Swift_FileSpool(__DIR__."/spool");
// Setup the transport and mailer
$transport = Swift_SpoolTransport::newInstance($spool);

// Create an instance of the plugin and register it
$plugin = new Swift_Plugins_DecoratorPlugin($replacements);
$mailer = Swift_Mailer::newInstance($transport);
$mailer->registerPlugin($plugin);

// Create the message
$message = Swift_Message::newInstance();
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You {fullname}, are our best client ever thanks " .
    " to the {transactions} transactions you made with us.");
$message->setFrom("mailout@exampleco.com", "exampleco");

// Send the email
foreach($users as $user) {
  $message->setTo($user["email"], $user["fullname"]);
  $result = $mailer->send($message);
}
echo "SPOOLED $result emails";
?>

Thank you so much, Jane.


SOLUTION:

With Yii PHP Framework.

You need Swiftmailer uploaded to a local directory and path 'class' pointing to Swiftmailer.php as in my config/main.php

In protected/config/main.php ...

'components'=>array(
.....

'mailer' => array(
                'class' => 'application.modules.swiftmailer.SwiftMailer',

                // Using SMTP:
                'mailer' => 'smtp',
                // security is optional
                // 'ssl' for "SSL/TLS" or 'tls' for 'STARTTLS'
                'security' => '', 
                'host'=>'mail.example.com',
                'from'=>'mailout@example.com',
                'username'=>'mailout@example.com',
                'password'=>'pw',

                // Using sendmail:
                //'mailer'=>'sendmail',

                // Logging
                // logs brief messages about message success or failhure
                'logMailerActivity' => 'true', 
                // logs additional info from SwiftMailer about connection details 
                // must be used in conjunction with logMailerActivity == true
                // check the send() method for realtime logging to console if required
                'logMailerDebug' => 'true', 
),
),

decorator.php - this makes the emails and sends them to the 'spool' file.

<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con){
    die('Could not connect: ' . mysql_error());
}

mysql_select_db('database', $con) or die(mysql_error()) ;

$sql = "SELECT * FROM tablename"; 
$result = mysql_query($sql, $con);
if( $result ){
while ($row = mysql_fetch_assoc($result)) {
    $user = array(
        'email' => $row['email'],
        'username' => $row['username'],
        'id' => $row['id']
    );
    $users[] = $user;
}
}
else{
  /* error! */
};


// Create the replacements array
$replacements = array();
foreach ($users as $user) {
  $replacements[$user["email"]] = array (
    "{username}" => $user["username"],
    "{transactions}" => $user["id"]
  );
}

$spool = new Swift_FileSpool(__DIR__."/spool");
// Setup the transport and mailer
$transport = Swift_SpoolTransport::newInstance($spool);

// Create an instance of the plugin and register it
$plugin = new Swift_Plugins_DecoratorPlugin($replacements);
$mailer = Swift_Mailer::newInstance($transport);
$mailer->registerPlugin($plugin);

// Create the message
$message = Swift_Message::newInstance();
$message->setSubject("Subject text");
$message->setBody("<b>Dear {username}</b>,<br><br>Perhaps you would like to try xyz circle. " .
    " thank you for the {transactions} transactions you made with us.", 'text/html');
$message->setFrom("example@example.com", "example name");
$message->addPart("Plain text HTML Body You {username}, are our best client ever thanks " .
    " thank you for the {transactions} transactions you made with us.", 'text/plain');

// Send the email
foreach($users as $user) {
  $message->setTo($user["email"], $user["username"]);
  $result = $mailer->send($message);
}
echo "SPOOLED $result emails";
?>

spoolsend.php - this runs the spool queue to send mail:

<?php
//create an instance of the spool object pointing to the right position in the filesystem
$spool = new Swift_FileSpool(__DIR__."/spool");

//create a new instance of Swift_SpoolTransport that accept an argument as Swift_FileSpool
$transport = Swift_SpoolTransport::newInstance($spool);

//now create an instance of the transport you usually use with swiftmailer
//to send real-time email
$realTransport = Swift_SmtpTransport::newInstance(
    "mail.example.com",
    "25"
)
    ->setUsername("example@example.com")
    ->setPassword("pw");

$spool = $transport->getSpool();
$spool->setMessageLimit(10);
$spool->setTimeLimit(100);
$sent = $spool->flushQueue($realTransport);

echo "SENT $sent emails";

?>

If anyone has any problems, let me know and I might be able to help out.

Was it helpful?

Solution

IT's better to use:

while ($row = mysqli_fetch_assoc($result)) {
    $user = array(
        'email' => $row['email'],
        'username' => $row['username'],
        'id' => $row['id']
    );
    $users[] = $user;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top