Skip to content
This repository has been archived by the owner on Aug 21, 2019. It is now read-only.

Commit

Permalink
schedule newsletters, choose sender
Browse files Browse the repository at this point in the history
Signed-off-by: Bruno Meilick <b@bnomei.com>
  • Loading branch information
bnomei committed May 23, 2019
1 parent fffac06 commit 5b91d0f
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 17 deletions.
5 changes: 5 additions & 0 deletions blueprints/fields/mj-example-schedule-date.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
label: Schedule Date UTC
type: date
#default: today
width: 1/2
format: YYYY-MM-DD
5 changes: 5 additions & 0 deletions blueprints/fields/mj-example-schedule-time.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
label: Schedule Time UTC
type: time
#default: now
width: 1/2
help: <a target="_blank" href="https://www.timeanddate.com/worldclock/timezone/utc">Current Time at UTC</a>
10 changes: 10 additions & 0 deletions blueprints/fields/mj-example-senders.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# global def
label: Sender
type: select
width: 1/1
# URL to route needs to be hardcoded if you use kirby version < 2.4.2
# https://github.com/getkirby/panel/issues/1035
options: http://YOUR_DOMAIN_HERE/kirby-mailjet/PLUGIN_HASH_HERE/json/senders.json
# since kirby version 2.4.2
#options: url
#url: kirby-mailjet/PLUGIN_HASH_HERE/json/senders.json
3 changes: 3 additions & 0 deletions blueprints/mj-example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ fields:
mjcontactslist: mj-example-contactslists
mjsegment: mj-example-segment
mjemail: mj-example-email
mjscheduledate: mj-schedule-date
mjscheduletime: mj-schedule-time
mjsenders: mj-senders
mjreminder: mj-example-save-reminder
mjpreview: mj-example-preview
mjtrans: mj-example-trans
Expand Down
86 changes: 72 additions & 14 deletions kirby-mailjet-class.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ public static function client()
private static $_from = null;
public static function senderAdress($emailadress = null)
{
if (!self::$_from) {
$apifrom = c::get('plugin.mailjet.from', $emailadress);
if (!self::$_from || $emailadress) {
$apifrom = $emailadress ? $emailadress : c::get('plugin.mailjet.from');

if ($apifrom && v::email($apifrom)) {
self::$_from = $apifrom;
Expand Down Expand Up @@ -276,6 +276,39 @@ public static function renderMustache($file, $mustachedata = [], $pluginFolder =
return $out;
}

/////////////////////////////////////
//
private static $_senders = null;
public static function senders()
{
$mj = self::client();
if (!$mj) {
return null;
}
if (self::$_senders) {
return self::$_senders;
}

$cl = array();
$exclude = c::get('plugin.mailjet.json-senders.exclude', []);
$response = $mj->get(Resources::$Sender, ['body' => null]);
if ($response->success()) {
foreach ($response->getData() as $r) {
if (in_array($r['Email'], $exclude) || strpos($r['Email'], '*') === 0 ) {
continue;
}
if (in_array($r['Name'], $exclude)) {
continue;
}

$cl[$r['Email']] = $r['Name'];
}
self::$_senders = $cl;
}

return $cl;
}

/////////////////////////////////////
//
private static $_segments = null;
Expand Down Expand Up @@ -561,7 +594,7 @@ public static function sendMail($params)
/////////////////////////////////////
// send newsletter
// default is just a test
public static function sendNewsletter($contactslistname, $campaign_body, $campaign_content, $testEmail = true)
public static function sendNewsletter($contactslistname, $campaign_body, $campaign_content, $testEmail = true, $schedule = null)
{
$jsonResponse = [ 'code' => 400]; // 'message' => 'Unknown Error'

Expand Down Expand Up @@ -601,6 +634,10 @@ public static function sendNewsletter($contactslistname, $campaign_body, $campai

$hasTestEmail = v::email($testEmail);
$hasPublish = $testEmail == 'Publish' || $testEmail == false;
$schedule = strtolower($schedule) == 'now' ? 'NOW' : $schedule;
if($schedule || $testEmail == 'Schedule') {
$hasPublish = false;
}

/////////////////////////////////
/// CAMPAIN GET/CREATE
Expand All @@ -614,7 +651,7 @@ public static function sendNewsletter($contactslistname, $campaign_body, $campai
// -2 : deleted
// -1 : archived draft
// 0 : draft
// 1 : programmed
// 1 : programmed => schedule
// 2 : sent
// 3 : A/X tesring
];
Expand Down Expand Up @@ -643,7 +680,7 @@ public static function sendNewsletter($contactslistname, $campaign_body, $campai

$found = true;
$campaign_id = $campaign['ID'];
$isDraft = $campaign['Status'] == 0;
$isDraft = $campaign['Status'] == 0 || $campaign['Status'] == 1;

// do not create or update new if exists but is not draft
if ($hasPublish && !$isDraft) {
Expand All @@ -657,6 +694,11 @@ public static function sendNewsletter($contactslistname, $campaign_body, $campai
$response = $mj->put(Resources::$Newsletter, ['id' => $campaign_id, 'body' => $campaign_body]);
if ($response->success()) {
$campaign_id = $campaign['ID'];

if(!$schedule) {
$mj->delete(Resources::$NewsletterSchedule, ['id' => $campaign_id]);
}

} else {
$jsonResponse['message'] = str_replace(['{newsletter}','{contactlist}'], [$campaign_id, $contactslistname], l::get('mailjet-error-newsletter-update-draft'));
self::pushLog(trim($jsonResponse['message']));
Expand Down Expand Up @@ -688,7 +730,7 @@ public static function sendNewsletter($contactslistname, $campaign_body, $campai
}

/////////////////////////////////
/// CAMPAIN BODY POST/PUT
/// CAMPAIGN BODY POST/PUT
///
// 2) post/put detail
/*
Expand Down Expand Up @@ -718,29 +760,45 @@ public static function sendNewsletter($contactslistname, $campaign_body, $campai
]);
if ($response->success()) {
$jsonResponse['code'] = 200;
$jsonResponse['message'] = str_replace(['{newsletter}','{email}','{service}'], [$campaign_id, $testEmail, ''], l::get('mailjet-success-newsletter-test'));
$jsonResponse['message'] = str_replace(['{newsletter}', '{email}', '{service}'], [$campaign_id, $testEmail, ''], l::get('mailjet-success-newsletter-test'));
self::pushLog(trim($jsonResponse['message']), false);
return $jsonResponse;
} else {
$params = [
'to' => $testEmail,
'from' => a::get($campaign_body, 'SenderEmail'),
'replyTo' => a::get($campaign_body, 'SenderEmail'),
'subject' => '[TEST] '.a::get($campaign_body, 'Subject'),
'body' => a::get($campaign_content, 'Html-part'),
'service' => self::EMAIL_SERVICE,
'to' => $testEmail,
'from' => a::get($campaign_body, 'SenderEmail'),
'replyTo' => a::get($campaign_body, 'SenderEmail'),
'subject' => '[TEST] ' . a::get($campaign_body, 'Subject'),
'body' => a::get($campaign_content, 'Html-part'),
'service' => self::EMAIL_SERVICE,

];
if (self::sendMail($params)) {
$jsonResponse['code'] = 200;
$jsonResponse['message'] = str_replace(['{newsletter}','{email}','{service}'], [$campaign_id, $testEmail, ' (transactional)'], l::get('mailjet-success-newsletter-test'));
$jsonResponse['message'] = str_replace(['{newsletter}', '{email}', '{service}'], [$campaign_id, $testEmail, ' (transactional)'], l::get('mailjet-success-newsletter-test'));
self::pushLog(trim($jsonResponse['message']), false);
return $jsonResponse;
} else {
// error already tracked
}
}

// SCHEDULE
} elseif ($schedule) {
$response = $mj->put(Resources::$NewsletterSchedule, ['id' => $campaign_id, 'body' => [
'date' => $schedule
]]);
if ($response->success()) {
$jsonResponse['code'] = 200;
$jsonResponse['message'] = str_replace(['{newsletter}','{contactlist}','{schedule}'], [$campaign_id, $contactslistID, $schedule], l::get('mailjet-success-newsletter-schedule'));
self::pushLog(trim($jsonResponse['message']), false);
return $jsonResponse;
} else {
$jsonResponse['message'] = str_replace(['{newsletter}','{contactlist}','{schedule}'], [$campaign_id, $contactslistID, $schedule], l::get('mailjet-error-newsletter-schedule'));
self::pushLog(trim($jsonResponse['message']).PHP_EOL.self::getResponseError($response));
return $jsonResponse;
}

// PUBLISH to contactslist
} elseif ($hasPublish) {
$response = $mj->post(Resources::$NewsletterSend, ['id' => $campaign_id]);
Expand Down
16 changes: 14 additions & 2 deletions kirby-mailjet-routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

return response::json($json, $code);
},

)
);

Expand Down Expand Up @@ -69,11 +69,23 @@
$json = $cl;
$code = 200;
}
} elseif ($file == 'senders.json') {
if (!$cl || f::modified($cacheFile) + c::get('plugin.mailjet.json.cache', 60*5) < time()) {
$cls = KirbyMailjet::senders();
if (count($cls) > 0) {
f::write($cacheFile, json_encode($cl));
$cl = $cls;
}
}
if ($cl) {
$json = $cl;
$code = 200;
}
}
}

return response::json($json, $code);
},

)
);
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "kirby-mailjet",
"description": "Kirby Mailjet makes sending emails with Mailjet simple.",
"version": "0.8.0",
"version": "0.9.0",
"author": "Bruno Meilick",
"type": "kirby-plugin",
"license": "Commercial"
Expand Down
19 changes: 19 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ But if you have your own toolchain to create responsive HTML code for emails you
- add attachements to emails
- add and remove Contacts from Contactslists
- test and publish Newsletters
- publish Newsletters on a Schedule
- choose Mailjet Sender Adress
- Panel Fields to access Contactslists and Segments
- Panel Buttons to send tests and publish (Kirby Opener required)
- example how to create responsive HTML emails
Expand Down Expand Up @@ -146,6 +148,10 @@ if(KirbyMailjet::sendMail($params)){
$senderEmail = KirbyMailjet::senderAdress();
// or
$senderEmail = KirbyMailjet::senderAdress('my@email.com');
// or
if ($page->mjsender()->isNotEmpty()) {
$senderEmail = $page->mjsender()->value();
}

// the subject is most important since that will be used
// to identify your Newsletter in combination with
Expand Down Expand Up @@ -193,6 +199,7 @@ KirbyMailjet::sendNewsletter(
$campaign_body,
$campaign_content,
'my@email.com', // email-adress to send test to or string 'Publish'
$schedule, // `null`/`'now'`, a timestamp or an ISO 8601 formatted date (`date('c')`) at UTC
);

// you can enable logging in config file like this
Expand All @@ -203,6 +210,18 @@ if(KirbyMailjet::hasErrors()) {
}
```

**schedule timezone convert example**
```php
$schedule = null;
if ($page->mjscheduledate()->isNotEmpty() && $page->mjscheduletime()->isNotEmpty()) {
$schedule = $page->mjscheduledate()->value() . 'T'. $page->mjscheduletime() . ':00';
$date = new \DateTime($schedule, new \DateTimeZone('Europe/Berlin'));
$date->setTimezone(new \DateTimeZone('UTC'));
$schedule = $date->format(\DateTimeInterface::ISO8601);
}

```

## Responsive HTML Emails Example

You can find the [example readme here](https://github.com/bnomei/kirby-mailjet/blob/master/example.md).
Expand Down

0 comments on commit 5b91d0f

Please sign in to comment.