Skip to content

Instantly share code, notes, and snippets.

@digitalpianism
Last active May 25, 2018 10:55
Show Gist options
  • Save digitalpianism/8e705f508c3693d69a577eb4b86626cc to your computer and use it in GitHub Desktop.
Save digitalpianism/8e705f508c3693d69a577eb4b86626cc to your computer and use it in GitHub Desktop.
Dirty Magento Shell script to send all transactional emails
<?php
/**
To run and send all emails:
php -f emailTemplateGenerator.php -- -email raphael@me.com
Tun run and send one email:
php -f emailTemplateGenerator.php -- -email raphael@me.com -template 46
*/
require_once 'abstract.php';
/**
* Magento Email Templates Generator Script
*
* @category Mage
* @package Mage_Shell
* @author Raphael Petrini <contact@digital-pianism.com>
*/
class Mage_Shell_Emailtemplatesgenerator extends Mage_Shell_Abstract {
protected $limit = 0;
protected $filter = "";
protected $templateId = "";
// select * from core_config_data where path like '%trans_email%';
const XML_PATH_EMAIL_SENDER_EMAIL = 'trans_email/ident_general/email';
const XML_PATH_EMAIL_SENDER_NAME = 'trans_email/ident_general/name';
// Dummy data
//protected $_dummyOrderIncrementId = 100018716;
protected $_dummyOrderIncrementId = 100000011;
protected $_dummyInvoiceIncrementId = 100000003;
protected $_dummyCreditmemoIncrementId = 100000004;
protected $_dummyShipmentIncrementId = 100000002;
/**
* Dummy Templates Variables
*
* @var array
*/
protected $templVars = array(
//"sender_name" => "Alannah Hill",
"product_name" => "Dummy Product",
"product_url" => "dummy-product.html",
"product_image" => "default",
"message" => "Dummy Message",
"increment_id" => 100000011,
"order_date" => "2011-03-07 02:30:59",
"direct_url" => "dummy-url.html",
"firstname" => "First Name",
"bday_code" => "dummycode",
//"store_name" => "Alannah Hill",
"certificate_numbers" => "dummy-certificate-number",
"amount" => 10,
"expire_on" => "2012-12-21 00:00:00",
"custom_message" => "dummy custom message",
"recipient_name" => "Dummy Recipient",
"productname" => "Dummy Product",
"specialprice" => 10,
"cartprice" => 25,
"extraproductcount" => 2,
"discount" => 100,
//"storeName" => "Alannah Hill",
"orderId" => 100000011,
// customer
"customerName" => "Dummy Customer",
"customerEmail" => "", // set via cli arg
"customer_name" => "Dummy Customer",
"custFirstName" => "Dummy First Name",
"itemList" => "Dummy item list",
"comment" => "dummy comment",
"items" => "dummy items",
"salable" => "yes",
"viewOnSiteLink" => "dummy-link"
);
/**
* Run script
*
*/
public function run() {
//$theme = Mage::getStoreConfig('design/theme/skin');
$theme = Mage::getSingleton('core/design_package')->setStore(1)->getTheme('template');
//$package = Mage::getStoreConfig('design/package/name');
/** @var Mage_Core_Model_Design_Package $package */
$package = Mage::getSingleton('core/design_package')->getPackageName();
/*$themeArgs = array('locale', 'layout', 'template', 'default', 'skin');
foreach($themeArgs as $arg) {
$themeVal = Mage::getSingleton('core/design_package')->getTheme($arg);
echo sprintf("package_theme[%s]=%s/%s\n", $arg, $package, $themeVal);
}*/
// setup vars
$this->templVars['sender_name'] = Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER_NAME);
$this->templVars['store_name'] = Mage::app()->getStore()->getName();
$this->templVars['storeName'] = Mage::app()->getStore()->getName();
if ($this->getArg('l')) {
$this->limit = $this->getArg('l');
}
if ($this->getArg('f')) {
$this->filter = $this->getArg('f');
}
// Display the help
if ($this->getArg('help')) {
$this->usageHelp();
exit();
}
// check email
if (!$this->getArg('email')) {
exit("Please specify a recipient email address e.g. php -f emailTemplateGenerator.php -- -email test@test.com \n");
}
elseif (!$this->isValidEmail($this->getArg('email'))) {
exit("Please specify a valid email address e.g. name@domain.com \n");
}
// template id
$this->templateId = $this->getArg('template');
$this->templVars['customerEmail'] = $this->getArg('email');
$customer = Mage::getModel('customer/customer')->setWebsiteId(1)->loadByEmail($this->templVars['customerEmail']);
if ($customer) {
//$this->templVars['customer_name'] = $customer->getName();
//$this->templVars['customerName'] = $customer->getName();
$this->templVars['customer'] = $customer;
echo sprintf("customer_name: %s\n", $this->templVars['customer_name']);
}
else {
echo sprintf("error: no customer for '%s'!\n", $this->templVars['customerEmail']);
}
//$packages = array('default', 'aw_mobile');
$packages = array('default');
// do for each theme
foreach($packages as $package) {
echo sprintf("set package_theme=%s/%s\n", $package, $theme);
Mage::getDesign()->setArea('frontend')->setPackageName($package)->setTheme($theme);
$cnt = $this->sendTemplateEmails();
echo sprintf("sent %d emails\n", $cnt);
}
//$templVars = $this->getTemplateEmailVars();
//echo sprintf("templVars=%s\n", print_r($templVars, true));
}
/**
*/
function getTemplateEmailVars() {
$templVars = array();
$templates = Mage::getResourceSingleton('core/email_template_collection');
foreach($templates as $template) {
//$templateId = $template->getTemplateId();
$templateVariablesArray = Mage::helper('core')->jsonDecode($template->getOrigTemplateVariables());
//echo sprintf("templateVariablesArray=%s\n", print_r($templateVariablesArray, true));
if (is_array($templateVariablesArray)) {
foreach ($templateVariablesArray as $key => $val) {
if (preg_match("/^var\s+[\w\-]+\./", $key)) {
echo sprintf("key:%s=%s\n", $key, $val);
}
/*
elseif (preg_match("/^var/", $key)) {
echo sprintf("key:%s=%s\n", $key, $val);
preg_match("/(var\s+)([\w\-]+)/", $key, $matches);
echo sprintf("matches=%s\n", print_r($matches, true));
if (!in_array($matches[2], $templVars)) {
$templVars[] = $matches[2];
}
}
*/
//echo sprintf("key:%s=%s\n", $key, $val);
}
}
}
sort($templVars);
return $templVars;
}
/**
*/
function sendTemplateEmails() {
$templates = Mage::getResourceSingleton('core/email_template_collection');
if (empty($templates)) {
die("no templates!");
}
$cnt = 0;
// Mage_Core_Model_Email_Template
foreach($templates as $template) {
$templateId = $template->getTemplateId();
// load from db core_email_template
//$emailTemplate = Mage::getModel('core/email_template')->loadByCode('custom_template');
// file system is the default template
//$emailTemplate = Mage::getModel('core/email_template')->loadDefault('custom_template');
if ($this->templateId && $this->templateId != $templateId) {
continue;
}
if ($this->limit != 0 && $cnt >= $this->limit) {
echo sprintf("email limit %d reached!\n", $this->limit);
break;
}
/*
skip plain text email template (no need to test them)
if ($template->getTemplateType() == Mage_Core_Model_Template::TYPE_TEXT) {
echo sprintf("skip template type '%s'!\n", Mage_Core_Model_Template::TYPE_TEXT);
continue;
}
*/
if (!empty($this->filter) && !preg_match(sprintf("/%s/i", $this->filter), $template->getData('template_code')) ) {
//echo sprintf("skip sending to template named '%s', failed filter '%s'\n", $template->getData('template_code'), $this->filter);
continue;
}
//$template->getData('template_code')
//$template->getTemplateCode();
echo sprintf("template .%03d: %d, %s, [%s]:%s\n", ($cnt + 1), $templateId, $template->getTemplateType(), $template->getData('template_code'), $template->getTemplateSubject());
// Get the original email variables
$templateVariablesArray = Mage::helper('core')->jsonDecode($template->getOrigTemplateVariables());
//echo sprintf("templateVariablesArray=%s\n", print_r($templateVariablesArray, true));
// Some emails need entire objects (order, invoice, customer, subscriber, wishlist) to be passed as variables
// We need to differentiate these different types of emails
$isDataEmail = false;
$isCustomerEmail = false;
$isSubscriptionEmail = false;
if (is_array($templateVariablesArray)) {
foreach (array_keys($templateVariablesArray) as $key) {
//echo sprintf("key=%s\n", $key);
// If we found an original email variable that contains one of these keywords
// We assume it's a data email
if (strpos($key,'$order.') || strpos($key,'$invoice.') || strpos($key,'$shipment') || strpos($key,'$creditmemo.') || strpos($key,'$customer.') || strpos($key,'subscriber.')) {
$isDataEmail = true;
break;
}
else {
continue;
}
}
}
/**
Note. var=$subscriber. is not adding to keys
*/
$txt = $template->getTemplateText();
//echo sprintf("TemplateText=%s\n", print_r($txt, true));
if (preg_match("/subscriber\./", $txt)) {
$isSubscriptionEmail = true;
}
// Increase the count
$cnt++;
// Get the template ID and sender
$emailSender = Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER_EMAIL);
echo sprintf("send email to '%s' from '%s'\n", $this->templVars['customerEmail'], $emailSender);
// If it's a data email
if ($isDataEmail) {
// We get the dummy data
$order = Mage::getModel('sales/order')->loadByIncrementId($this->_dummyOrderIncrementId);
$invoice = Mage::getModel('sales/order_invoice')->loadByIncrementId($this->_dummyInvoiceIncrementId);
$shipment = Mage::getModel('sales/order_shipment')->loadByIncrementId($this->_dummyShipmentIncrementId);
//$creditmemo = Mage::getModel('sales/order_creditmemo')->loadByIncrementId($this->_dummyCreditmemoIncrementId);
$creditmemo = Mage::getModel('sales/order_creditmemo')->load(4);
$customer = Mage::getModel('customer/customer')->setWebsiteId(1)->loadByEmail($this->templVars['customerEmail']);
//$subscriber = Mage::getModel('newsletter/subscriber')->setWebsiteId(1)->loadByEmail($this->templVars['customerEmail'])
// mailer used to send the email
$mailer = Mage::getModel('core/email_template_mailer');
echo(sprintf("%s->var=%s", __METHOD__, print_r($mailer, true)) );
// Add some info to the email
$emailInfo = Mage::getModel('core/email_info');
$emailInfo->addTo($this->templVars['customerEmail']);
$mailer->addEmailInfo($emailInfo);
// Set all required params and send emails
$mailer->setSender($emailSender);
$mailer->setTemplateId($templateId);
// Retrieve specified view block from appropriate design package (depends on emulated store)
$paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())->setIsSecureMode(true);
$paymentBlock->getMethod()->setStore($storeId);
$paymentBlockHtml = $paymentBlock->toHtml();
$mailer->setTemplateParams(array(
'customer' => $customer,
'order' => $order,
'invoice' => $invoice,
'creditmemo' => $creditmemo,
'shipment' => $shipment,
'billing' => $order->getBillingAddress(),
'payment_html' => $paymentBlockHtml
)
);
echo sprintf("1. %s->send()\n", get_class($mailer));
$mailer->send();
}
else if ($isSubscriptionEmail) {
$subscriber = Mage::getModel('newsletter/subscriber')->setWebsiteId(1)->loadByEmail($this->templVars['customerEmail']);
$subscriber->setData("subscriber_coupon", "testCode");
// Mailer used to send the email
$mailer = Mage::getModel('core/email_template_mailer');
// Add some info to the email
$emailInfo = Mage::getModel('core/email_info');
$emailInfo->addTo($this->templVars['customerEmail']);
$mailer->addEmailInfo($emailInfo);
// Set all required params and send emails
$mailer->setSender($emailSender);
$mailer->setTemplateId($templateId);
$mailer->setTemplateParams(array(
'subscriber' => $subscriber
)
);
echo sprintf("2. %s->send()\n", get_class($mailer));
echo(sprintf("%s->var=%s", __METHOD__, print_r($mailer, true)) );
$mailer->send();
}
else {
$recepientName = $this->templVars['customer_name'];
$storeId = Mage::app()->getStore()->getId();
echo sprintf("3. %s->send()\n", get_class(Mage::getModel('core/email_template')));
echo $templateId . "|". $emailSender . "|". $this->templVars['customerEmail'] . "|". $recepientName . "|". $storeId . "\n";
$sender = array(
'name' => Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER_NAME),
'email' => Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER_EMAIL)
);
$translate = Mage::getSingleton('core/translate');
// ->setTemplateSubject($template->getTemplateSubject())
Mage::getModel('core/email_template')->sendTransactional(
$templateId,
$sender,
$this->templVars['customerEmail'],
$recepientName,
$this->templVars,
$storeId
);
$translate->setTranslateInline(true);
}
sleep(1);
}
return $cnt;
}
/**
* Retrieve Usage Help Message
*
*/
public function usageHelp()
{
return <<<USAGE
Usage: php -f emailTemplateGenerator.php -- [options]
--email <email_address> Set up the recipient email
--template <template_id> See Magento: System -> Transactional Emails
help This help
<indexer> Comma separated indexer codes or value "all" for all indexers
USAGE;
}
/**
* Validate Email Address
*
*/
function isValidEmail($emailRecipient)
{
return filter_var($emailRecipient, FILTER_VALIDATE_EMAIL);
}
}
$shell = new Mage_Shell_Emailtemplatesgenerator();
try {
$shell->run();
}
catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment