Blog

Programmatically Subscribing a Customer to the Newsletter List

Recently we had to import a list of newsletter subscribers into Magento. We had already loaded all the customers, but now we needed to subscribe all of the customers that had subscribed on the customer’s old site on the new. The following code (simplified for display here) did the trick!

<?php
define('CRLF', 'rn');
require_once("<path to your app folder>Mage.php");
Mage::app();
$email = "joe@blow.com";
// THE "EASY" WAY (but sends a confirmation email to the customer
$subscriber = Mage::getModel('newsletter/subscriber')->subscribe($email);
// THE "HARD" WAY (Doesn't send confirmation email to customer)
// load up the customer we want to subscribe
$customer = Mage::getModel('customer/customer')
->setWebsiteId(1)
->loadByEmail($email);
// if we found the customer
if ($customer->getId()){
// load up the subscriber if possible
$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
if (!$subscriber->getId() 
|| $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED 
|| $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE) {
$subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
$subscriber->setSubscriberEmail($email);
$subscriber->setSubscriberConfirmCode($subscriber->RandomSequence());
}
$subscriber->setStoreId(Mage::app()->getStore()->getId());
$subscriber->setCustomerId($customer->getId());
try {
$subscriber->save();
}
catch (Exception $e) {
throw new Exception($e->getMessage());
}
}

5 Comments

  1. panticz

    Hi, here a mutch easier soluntion:

    setImportMode(true)->subscribe($email);

    # get just generated subscriber
    $subscriber = Mage::getModel(‘newsletter/subscriber’)->loadByEmail($email);

    # change status to “subscribed” and save
    $subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
    $subscriber->save();
    }
    ?>

  2. panticz

    The source code above is unfortunately not show up correctly, here a link to the script:

    http://www.panticz.de/Magento-Newsletter-subscriber-import

    BR

    Pawel

  3. […] With some help from ifuelinteractive […]

  4. Anja

    Exactly what I needed! I needed to load customers first then subscribe them, not make new subscribers :-). Thanks!

  5. Dmytro

    ty very much, works like a charm!

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>