Skip to content

Commit

Permalink
Added mail template logging
Browse files Browse the repository at this point in the history
  • Loading branch information
jawngee committed May 10, 2019
1 parent adaace7 commit 1a956fb
Show file tree
Hide file tree
Showing 5 changed files with 172 additions and 3 deletions.
32 changes: 32 additions & 0 deletions classes/Logging/MailTemplateLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Stem\MailTemplates\Logging;

class MailTemplateLog {
public static function LogSuccess($responseId, $response, $template, $to, $bcc, $data) {
/** @var \WPDB */
global $wpdb;
$wpdb->insert('stem_mail_template_log', [
'template' => $template,
'email_to' => serialize($to),
'email_bcc' => serialize($bcc),
'status' => (int)1,
'data' => serialize($data),
'responseId' => $responseId,
'response' => $response
]);
}

public static function LogError($template, $to, $bcc, $data, $error) {
/** @var \WPDB */
global $wpdb;
$wpdb->insert('stem_mail_template_log', [
'template' => $template,
'email_to' => serialize($to),
'email_bcc' => serialize($bcc),
'status' => (int)0,
'data' => serialize($data),
'error' => $error
]);
}
}
21 changes: 19 additions & 2 deletions classes/Models/MailTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

use Mailgun\Mailgun;
use Mailgun\Message\MessageBuilder;
use Mailgun\Model\Message\SendResponse;
use Stem\Core\Context;
use Stem\MailTemplates\Logging\MailTemplateLog;
use Stem\Models\Attachment;
use Stem\Models\Post;
use Stem\Models\Utilities\CustomPostTypeBuilder;
Expand Down Expand Up @@ -177,6 +179,7 @@ public function send($email=null, $data=[], $inline=[], $attachments=[]) {
return false;
}


$smtpConfig = get_option('wp_mail_smtp');

$mailgunKey = arrayPath($smtpConfig, 'mailgun/api_key', null);
Expand All @@ -192,25 +195,31 @@ public function send($email=null, $data=[], $inline=[], $attachments=[]) {
$messageBldr = new MessageBuilder();
$messageBldr->setFromAddress($fromEmail, ['full_name' => $fromName]);

$logToEmails = [];
$toSet = false;
if ($email != null) {
$toSet=true;
if (is_array($email)) {
foreach($email as $emailAddress) {
$logToEmails[] = $emailAddress;
$messageBldr->addToRecipient($emailAddress);
}
} else {
$logToEmails[] = $email;
$messageBldr->addToRecipient($email);
}
}

foreach($this->toEmails as $toEmail) {
$toSet=true;
$logToEmails[] = $toEmail->email;
$messageBldr->addToRecipient($toEmail->email);
}

$logBccEmails = [];
foreach($this->bccEmails as $bccEmail) {
$messageBldr->addToRecipient($bccEmail->email);
$logBccEmails[] = $bccEmail->email;
$messageBldr->addBccRecipient($bccEmail->email);
}

$messageBldr->setSubject($this->subject);
Expand Down Expand Up @@ -261,9 +270,13 @@ public function send($email=null, $data=[], $inline=[], $attachments=[]) {

if ($toSet) {
$mg = Mailgun::create($mailgunKey);
$mg->messages()->send($domain, $messageBldr->getMessage());

/** @var SendResponse $response */
$response = $mg->messages()->send($domain, $messageBldr->getMessage());
MailTemplateLog::LogSuccess($response->getId(), $response->getMessage(), $this->slug, $logToEmails, $logBccEmails, $data);
return true;
} else {
MailTemplateLog::LogError($this->slug, $logToEmails, $logBccEmails, $data, 'No email addresses specified.');
}

return false;
Expand Down Expand Up @@ -310,7 +323,11 @@ public static function sendTemplate($slugOrTemplate, $email = null, $data=[], $i
$template = Context::current()->modelForPost($templatePost);
if(!empty($template)) {
return $template->send($email, $data, $inline, $attachments);
} else {
MailTemplateLog::LogError($slugOrTemplate, [$email], null, $data, 'Template not found.');
}
} else {
MailTemplateLog::LogError($slugOrTemplate, [$email], null, $data, 'Template not found.');
}
}

Expand Down
71 changes: 71 additions & 0 deletions classes/UI/MailLogList.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

namespace Stem\MailTemplates\UI;

use Carbon\Carbon;
use Stem\UI\ListTable;

class MailLogList extends ListTable {

public function __construct($args = []) {
parent::__construct([
'singlur' => 'Mail Log',
'plural' => 'Mail Logs',
'ajax' => false,
'screen' => (!empty($args['screen'])) ? $args['screen'] : null
]);
}

public function get_columns() {
return [
'date' => 'Date',
'template' => 'Template',
'to' => 'To',
'error' => 'Error',
'responseId' => 'Response ID',
'response' => 'Response',
];
}

public function prepare_items() {
/** @var \WPDB $wpdb */
global $wpdb;

$offset = ($this->get_pagenum() - 1) * 100;
$this->items = $wpdb->get_results("select * from stem_mail_template_log order by id desc limit 100 offset {$offset}");
$this->_column_headers = [$this->get_columns(), [], []];
$total = $wpdb->get_var("select count(id) from stem_mail_template_log");
$this->set_pagination_args([
'total_items' => $total,
'per_page' => 100,
'total_pages' => ceil($total / 100)
]);
}

protected function column_date($item) {
$date = Carbon::parse($item->created_at);
return $date->format('n/j/Y g:i a');
}

protected function column_template($item) {
return $item->template;
}

protected function column_to($item) {
$toData = unserialize($item->email_to);

return implode(', ', $toData);
}

protected function column_error($item) {
return $item->error;
}

protected function column_responseId($item) {
return $item->responseId;
}

protected function column_response($item) {
return $item->response;
}
}
49 changes: 49 additions & 0 deletions migrations/20190510002011_mail_template_logging.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php


use Phinx\Migration\AbstractMigration;

class MailTemplateLogging extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* addCustomColumn
* renameColumn
* addIndex
* addForeignKey
*
* Any other destructive changes will result in an error when trying to
* rollback the migration.
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
$table = $this->table('stem_mail_template_log', ['id' => false, 'primary_key' => 'id', 'engine' => 'innodb', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci']);
$table
->addColumn('id', 'biginteger', ['signed' => false, 'null' => false, 'identity' => true])
->addColumn('template', 'string', ['length' => 255, 'null' => false, 'collation' => 'utf8mb4_unicode_ci'])
->addColumn('email_to', 'text', ['collation' => 'utf8mb4_unicode_ci'])
->addColumn('email_bcc', 'text', ['collation' => 'utf8mb4_unicode_ci'])
->addColumn('status', 'integer', ['signed' => true, 'null' => false, 'default' => (int)0])
->addColumn('data', 'text', ['collation' => 'utf8mb4_unicode_ci'])
->addColumn('error', 'text', ['collation' => 'utf8mb4_unicode_ci'])
->addColumn('responseId', 'string', ['length' => 255, 'collation' => 'utf8mb4_unicode_ci'])
->addColumn('response', 'text', ['collation' => 'utf8mb4_unicode_ci'])
->addTimestamps()
->create();
}
}
2 changes: 1 addition & 1 deletion stem-mail-template.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Plugin URI: https://github.com/jawngee/the-wonder
Description: Model for mail templates
Author: interfacelab
Version: 0.2.1
Version: 0.2.2
Author URI: http://interfacelab.io
*/

Expand Down

0 comments on commit 1a956fb

Please sign in to comment.