Ejemplo n.º 1
0
 public function __construct(MailgunApi $api)
 {
     $this->_api = $api;
     $this->_from = $api->getFrom();
     $this->_tags = $api->getTags();
     $this->_campaignId = $api->getCampaignId();
     $this->_enableDkim = $api->getIsDkimEnabled();
     $this->_enableTestMode = $api->getIsTestModeEnabled();
     $this->_enableTracking = $api->getIsTrackingEnabled();
     $this->_clicksTrackingMode = $api->getClicksTrackingMode();
     $this->_enableOpensTracking = $api->getIsOpensTrackingEnabled();
 }
Ejemplo n.º 2
0
 public function __construct(MailgunApi $api)
 {
     if (self::$_legacyAttachMode === null) {
         self::$_legacyAttachMode = !class_exists('CURLFile', false);
     }
     $this->_api = $api;
     $this->_from = $api->getFrom();
     $this->_tags = $api->getTags();
     $this->_campaignId = $api->getCampaignId();
     $this->_enableDkim = $api->getIsDkimEnabled();
     $this->_enableTestMode = $api->getIsTestModeEnabled();
     $this->_enableTracking = $api->getIsTrackingEnabled();
     $this->_clicksTrackingMode = $api->getClicksTrackingMode();
     $this->_enableOpensTracking = $api->getIsOpensTrackingEnabled();
 }
 public function run($args)
 {
     if (!(int) $this->runEveryXDays || (int) $this->runEveryXDays > 7) {
         throw new Exception('Must be run every 1 -> 7 days');
     }
     $runEveryUnix = (int) $this->runEveryXDays * 24 * 60 * 60;
     // run a query to get each organisation with the unsubscribe total for the last week and ever
     $organisations = Yii::app()->db->createCommand("\n\n\t\t\tSELECT o.id, o.title, o.email_address\n\n\t\t\tFROM organisation o\n\n\t\t\tWHERE o.id != 10 -- ten is the application organisation\n\n\t\t")->queryAll();
     // get a count of recent unsubscribes
     $this->recentUnsubscribeResults = Yii::app()->db->createCommand("\n\n\t\t\tSELECT origin_organisation_id as id, COUNT(DISTINCT email) as total\n\n\t\t\tFROM (\n\t\t\t\n\t\t\t\tSELECT s.email, s.id, s.origin_organisation_id\n\t\t\t\tFROM suppression_list sl, store s, organisation o\n\t\t\t\tWHERE sl.store_id IS NOT NULL\n\t\t\t\t\tAND s.id = sl.store_id\n\t\t\t\t\tAND s.origin_organisation_id != 10\n\t\t\t\t\tAND o.id = s.origin_organisation_id\n\t\t\t\t\tAND s.email IS NOT NULL\n\t\t\t\t\t-- INVITES DO HAVE CAMPAIGN_IDs IN THE SUPPRESSION TABLE >> AND sl.campaign_id IS NULL \n\t\t\t\t\tAND sl.type = 1\n\t\t\t\t\tAND sl.`date` >= '" . date("Y-m-d H:i:s", time() - $runEveryUnix) . "'\n\t\t\t)\n\t\t\tAS t\n\n\t\t\tGROUP BY origin_organisation_id\n\n\t\t")->queryAll();
     // get a count of all unsubscribes
     $this->totalUnsubscribeResults = Yii::app()->db->createCommand("\n\n\t\t\tSELECT origin_organisation_id as id, COUNT(DISTINCT email) as total\n\n\t\t\tFROM (\n\t\t\t\n\t\t\t\tSELECT s.email, s.id, s.origin_organisation_id\n\t\t\t\tFROM suppression_list sl, store s, organisation o\n\t\t\t\tWHERE sl.store_id IS NOT NULL\n\t\t\t\t\tAND s.id = sl.store_id\n\t\t\t\t\tAND s.origin_organisation_id != 10\n\t\t\t\t\tAND o.id = s.origin_organisation_id\n\t\t\t\t\tAND s.email IS NOT NULL\n\t\t\t\t\t-- INVITES DO HAVE CAMPAIGN_IDs IN THE SUPPRESSION TABLE >> AND sl.campaign_id IS NULL\n\t\t\t\t\tAND sl.type = 1\n\t\t\t\t\tAND sl.`date` > '2015-02-13 16:34:00' -- when the auto suppressions appear to stop and sending bounces start in the live database.\n\t\t\t)\n\t\t\tAS t\n\n\t\t\tGROUP BY origin_organisation_id\n\n\t\t")->queryAll();
     $basebody = "\nHi,\n\n[[organisation_title]] has had [[recent_unsubscribes]] unsubscribes in the last " . $this->runEveryXDays . " day" . ($this->runEveryXDays == 1 ? "" : "s") . " and [[total_unsubscribes]] unsubscribes in total.\n\nYou can download a file containing all unsubscribes with timestamps by logging into Application Name:\n\n[[link_to]]\n\nThank you,\n\n" . Yii::app()->name . "\n\n";
     $configs = Yii::app()->db->createCommand("SELECT * FROM `config` WHERE `key` IN ('host', 'https')")->queryAll();
     if (sizeof($configs) < 2) {
         throw new CException("\n\n\n===\nDomain or HTTPS config not yet set. View any admin area page in a browser to remedy this.\n===\n\n");
     }
     foreach ($configs as $config) {
         $params[$config['key']] = $config['value'];
     }
     foreach ($organisations as $organisation) {
         if (!strlen($organisation['email_address'])) {
             continue;
         }
         // skip
         $to = $organisation['email_address'];
         if (ENVIRONMENT !== 'PRODUCTION') {
             $to = Yii::app()->params['adminEmail'];
         }
         $sendbody = preg_replace(array("@\\[\\[organisation_title\\]\\]@", "@\\[\\[recent_unsubscribes\\]\\]@", "@\\[\\[total_unsubscribes\\]\\]@", "@\\[\\[link_to\\]\\]@"), array($organisation['title'], $this->getRecentUnsubscribesForOrganisation($organisation['id']), $this->getTotalUnsubscribesForOrganisation($organisation['id']), 'http' . ((int) $params['https'] === 1 ? 's' : '') . '://' . $params['host'] . '/unsubscribes'), $basebody);
         //exit('to: ' . $to . ' - subject: ' . $this->emailSubject . ' - body length: ' . strlen($sendbody));
         $mailgunApi = new MailgunApi(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']);
         $message = $mailgunApi->newMessage();
         $message->setFrom(Yii::app()->params['fromEmail'], Yii::app()->name);
         $message->addTo($to);
         $message->setSubject($this->emailSubject);
         $message->setText($sendbody);
         $message->addTag('Unsubscribes');
         $message->send();
     }
 }
Ejemplo n.º 4
0
 public function run($args)
 {
     $campaignSuccess = false;
     $configs = Yii::app()->db->createCommand("SELECT * FROM `config` WHERE `key` IN ('host', 'https')")->queryAll();
     if (sizeof($configs) < 2) {
         throw new CException("\n\n\n===\nDomain or HTTPS config not yet set. View any admin area page in a browser to remedy this.\n===\n\n");
     }
     foreach ($configs as $config) {
         $configParams[$config['key']] = $config['value'];
     }
     date_default_timezone_set("Europe/London");
     print "Getting campaigns to process \n";
     $CampaignCollection = Campaign::model()->findAll(array('with' => array('query', 'groups' => array('with' => array('email_template'))), "condition" => "processing = 0 AND status = :status AND invite = 0", "params" => array(":status" => Campaign::STATUS_QUEUED)));
     print count($CampaignCollection) . ' campaigns to process' . "\n";
     $campaignIDs = [];
     foreach ($CampaignCollection as $Campaign) {
         $campaignIDs[] = $Campaign->id;
         print "Will process Campaign ID: " . $Campaign->id . " \n";
     }
     $command = Yii::app()->db->createCommand();
     $command->update('campaign', array("processing" => 1), array('in', 'id', $campaignIDs));
     foreach ($CampaignCollection as $Campaign) {
         /* sending logic */
         /* create mailgun campaign id */
         $mailgunApi = new MailgunCampaign(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']);
         // Check if the campaign ID exists
         try {
             $checkCampaignResponse = $mailgunApi->getCampaign(Yii::app()->params['insiderEmailDomain'], $Campaign->id);
         } catch (Exception $e) {
             $checkCampaignResponse = false;
         }
         if (!$checkCampaignResponse) {
             $mailgunCampaignResponse = $mailgunApi->createCampaign(Yii::app()->params['insiderEmailDomain'], array("name" => $Campaign->name, "id" => $Campaign->id));
         } else {
             $mailgunCampaignResponse['campaign'] = $checkCampaignResponse;
         }
         /* Example Response
         			Array
         			(
         				[message] => Campaign created
         				[campaign] => Array
         					(
         						[clicked_count] => 0
         						[opened_count] => 0
         						[submitted_count] => 0
         						[unsubscribed_count] => 0
         						[bounced_count] => 0
         						[id] => 691
         						[name] => Hicks 2
         						[created_at] => Tue, 24 Feb 2015 13:34:25 GMT
         						[delivered_count] => 0
         						[complained_count] => 0
         						[dropped_count] => 0
         					)
         
         			)
         			*/
         $Store = new Store();
         /* loop groups */
         /* load & render template (campaign_group) */
         foreach ($Campaign->groups as $CampaignGroup) {
             $mailgunApi = new MailgunApi(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']);
             $mailgunApi->enableTracking();
             $mailgunApi->enableOpensTracking();
             $mailgunApi->enableClicksTracking();
             $message = $mailgunApi->newMessage();
             $message->setFrom(Yii::app()->params['fromEmail'], Yii::app()->name);
             $message->setSubject($CampaignGroup->subject);
             $message->setCampaignId($mailgunCampaignResponse['campaign']['id']);
             $message->setHtml($CampaignGroup->email_template->parsedHtml($configParams));
             // send variables to mailgun so that bounces and opens are easier to deal with.
             $message->addVar('campaign_id', $Campaign->id);
             $message->addVar('group_id', $CampaignGroup->id);
             //get contacts
             $CampaignContactCollection = CampaignContact::model()->findAll(array('with' => array('contact2outcomes' => array('index' => 'campaign_outcome_id')), "condition" => "\n\t\t\t\t\t\tgroup_id = :groupid\n\t\t\t\t\t\tAND `t`.`status` = 0\n\t\t\t\t\t", "params" => array(":groupid" => $CampaignGroup->id), 'index' => 'warehouse_id'));
             echo sizeof($CampaignContactCollection);
             // get the contact rows for the above campaigncontact rows
             $Criteria = new CDbCriteria();
             $Criteria->index = 'contact_warehouse_id';
             $Contacts = CleanWarehouse::model()->findAllByPk(array_keys($CampaignContactCollection), $Criteria);
             $chunkedCampaignContacts = array_chunk($CampaignContactCollection, 1000, true);
             foreach ($chunkedCampaignContacts as $campaign1000) {
                 //echo 'C';
                 $transaction = $Campaign->dbConnection->beginTransaction();
                 $campaign1000IDs = array();
                 $sentCount = 0;
                 $message->resetTo();
                 foreach ($campaign1000 as $warehouse_id => $CampaignContact) {
                     //echo '.';
                     $campaign1000IDs[] = $CampaignContact->id;
                     $thisContact = $Contacts[$warehouse_id];
                     $standardTags = array('first_name' => $thisContact->first_name, 'last_name' => $Store->decryptLastName($thisContact->last_name), 'email' => $Store->decryptEmail($thisContact->email), 'insider_unsubscribe' => 'http' . ($configParams['https'] ? 's' : '') . '://' . $configParams['host'] . Yii::app()->urlManager->createUrl('data/campaignUnsubscribe', array('campaign_id' => $Campaign->id, 'campaign_hash' => $Campaign->hash, 'campaign_contact_id' => $CampaignContact->id, 'campaign_contact_hash' => $CampaignContact->hash)), 'warehouse_id' => $warehouse_id);
                     $campaignTags = $CampaignGroup->email_template->returnOutcomeTagsToUrls($configParams, $Campaign, $CampaignContact->contact2outcomes);
                     $parsedTagsArray = array_merge($standardTags, $campaignTags);
                     if (ENVIRONMENT === 'PRODUCTION') {
                         $message->addTo($Store->decryptEmail($thisContact->email), $thisContact->first_name . ' ' . $Store->decryptLastName($thisContact->last_name), $parsedTagsArray);
                     } else {
                         $message->addTo("*****@*****.**", $thisContact->first_name . ' ' . $Store->decryptLastName($thisContact->last_name), $parsedTagsArray);
                     }
                     $sentCount++;
                 }
                 /* send email to mailgun */
                 try {
                     $response = $message->send();
                     $command = Yii::app()->db->createCommand();
                     $command->update('campaign_contact', array("status" => CampaignContact::STATUS_SENT, "processing" => 0), array('in', 'id', $campaign1000IDs));
                     $transaction->commit();
                     $campaignSuccess = true;
                     echo 'Success';
                 } catch (Exception $e) {
                     //print $e->getMessage();
                     // mailgun returned an error - we rollback the transaction and remove the number of failed ids from the sent count
                     // consider mainatining a fail count??
                     $sentCount -= count($campaign1000);
                     $command = Yii::app()->db->createCommand();
                     $command->update('campaign_contact', array("status" => CampaignContact::STATUS_MAILGUN_ERROR, "processing" => 0), array('in', 'id', $campaign1000IDs));
                     $transaction->commit();
                     $msg = print_r($e, true);
                     $msg .= print_r($message, true);
                     mail('*****@*****.**', 'Mailgun error', $msg);
                 }
             }
         }
         if ($campaignSuccess) {
             $Campaign->status = Campaign::STATUS_HAS_BEEN_RUN;
         } else {
             $Campaign->status = Campaign::STATUS_ERROR_SEND;
         }
         $Campaign->processing = 0;
         $Campaign->save(true, array("processing", "status"));
         print "Completed processing " . $Campaign->id . " \n";
         $Campaign->refresh();
         print "Status of campaign was " . $Campaign->getStatusText() . "\n\n";
     }
 }
Ejemplo n.º 5
0
 public function sendPasswordResetEmail()
 {
     $mailgunApi = new MailgunApi(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']);
     $message = $mailgunApi->newMessage();
     $message->setFrom(Yii::app()->params['fromEmail'], Yii::app()->name);
     $message->addTo($this->email, $this->fullName);
     $message->setSubject('Your password reset request');
     $renderedView = Yii::app()->controller->renderPartial('//mail/resetPassword', array('name' => $this->first_name, 'resetLink' => 'http://' . Yii::app()->request->serverName . '/reset-password?hash=' . $this->updateResetHash()), true);
     $message->setHtml($renderedView);
     $message->addTag('Password reset');
     $message->send();
 }
Ejemplo n.º 6
0
 public function __construct($domain, $key)
 {
     //$this->_domain = $domain;
     parent::__construct($domain, $key);
 }
Ejemplo n.º 7
0
 public function sendTest($toEmail, $subject, $body)
 {
     // In test mode, we should send 9 emails - one from each organisation
     // The subject and body content should be as it is in the form, except we won't have a full URL, so we can use an example
     // Parse content including tags
     $parsedContent = $this->parseEmailContent($subject, $body, array('first_name' => '%recipient.first_name%', 'last_name' => '%recipient.last_name%', 'invite_url' => '%recipient.invite_url%', 'unsubscribe_url' => '%recipient.unsubscribe_url%'));
     $responses = array();
     // Let's load all the organisations, we'll need them later
     $Organisations = Organisation::model()->findAll(array('condition' => 'id != :id', 'params' => array(':id' => 10), 'index' => 'id'));
     $mailgunApi = new MailgunApi(Yii::app()->params['insiderEmailDomain'], Yii::app()->params['mailgun']['key']);
     // Loop the organisations and send an email for each one
     foreach ($Organisations as $Organisation) {
         if (strlen($Organisation->email_template)) {
             $message = $mailgunApi->newMessage();
             $message->setFrom('email@' . Yii::app()->params['insiderEmailDomain'], Yii::app()->name);
             $message->addTo($toEmail, Yii::app()->user->first_name . ' ' . Yii::app()->user->last_name, array('first_name' => Yii::app()->user->first_name, 'last_name' => Yii::app()->user->last_name, 'invite_url' => 'http://example.com/#-invite-url-', 'unsubscribe_url' => 'http://example.com/#-unsubscribe-url-'));
             $message->setSubject($parsedContent['subject']);
             $message->addTag('test');
             $renderedView = Yii::app()->controller->renderPartial('//mail/organisation-templates/' . $Organisation->email_template, array('body' => $parsedContent['body']), true);
             $message->setHtml($renderedView);
             $response = $message->send();
             if ($response['id']) {
                 $responses[] = $response['id'];
             } else {
                 $errors[] = $response;
             }
         } else {
         }
     }
     if (!sizeof($errors)) {
         Yii::app()->user->setFlash('success', sizeof($responses) . ' test emails sent. Check the inbox of ' . $_POST['Campaign']['email_test_recipient']);
     } else {
         Yii::app()->user->setFlash('error', 'There was an error sending some or all of the emails. ' . sizeof($responses) . ' test were emails sent. ' . $errors . ' were unset due to errors. Check the inbox of ' . $_POST['Campaign']['email_test_recipient']);
     }
     //$this->refresh();
 }
Ejemplo n.º 8
0
 public function actionForgot()
 {
     if (Yii::$app->request->post()) {
         $cpf = new User();
         $cpf->load(Yii::$app->request->post());
         $cpf->cpf = str_pad(ereg_replace('[^0-9]', '', $cpf->cpf), 11, '0', STR_PAD_LEFT);
         /// $usuario = User::find()->where(['email'=>$email])->one();
         //$usuario = User::findOne($cpf);
         //   echo($usuario->cpf);
         $usuario = new User();
         $usuario = User::findOne($cpf->cpf);
         //    print_r($usuario);
         if ($usuario != null) {
             $domain = 'sandbox0d88942972964b89b6b8ef12520db517.mailgun.org';
             $key = 'key-4ff7c7a5e38505ed435d60be7006c3a2';
             $mailgun = new \MailgunApi($domain, $key);
             $senha = $usuario->senhaAleatoria($usuario->cpf);
             $message = $mailgun->newMessage();
             $message->setFrom('*****@*****.**', 'SOS-UFAM');
             $message->addTo($usuario->email);
             //destinatario...
             $message->setSubject('Nova Senha');
             $message->setText('Sua nova senha temporária é: ' . $senha);
             $message->send();
             return $this->render('enviada', ['email' => $usuario->email]);
         } else {
             return $this->render('naoachouemail', ['cpf' => $cpf->cpf]);
         }
     } else {
         $model = new User();
         return $this->render('forgot', ['model' => $model]);
     }
 }
Ejemplo n.º 9
0
 public function actionRecuperarsenha()
 {
     if (Yii::$app->request->post()) {
         $email = Yii::$app->request->post('email');
         $usuario = Usuario::find()->where(['email' => $email])->one();
         if ($usuario != null) {
             $domain = 'sandbox081c87f9e07a4f669f46f26af7261c2a.mailgun.org';
             $key = 'key-f0dc85b59a45bcda5373019f605ce034';
             $mailgun = new \MailgunApi($domain, $key);
             $message = $mailgun->newMessage();
             $message->setFrom('*****@*****.**', 'Admin-Atv Complementares');
             $message->addTo($usuario->email, $usuario->name);
             //destinatario...
             $message->setSubject('Nova Senha');
             $message->setText('Sua nova senha temporária é: ' . $usuario->senhaAleatoria());
             $message->send();
             return $this->render('senhaenviada');
         } else {
             return $this->render('emailnaoencontrado');
         }
     } else {
         return $this->render('recuperarsenha');
     }
 }