Thursday, June 23, 2011

To insert newsletter subscriber email into database table in magento


When you want to get just a big bulk list of emails from a previous email account you had set up and wanted to import it into your Magento subscriber database there are a few ways to do it.
Personally I prefer writing it via an SQL statement though you can use the inbuilt subscribe function for Magento. The problem with the subscribe function is that it will notify the customer a newsletter subscription success email. If you don’t want that here’s what you can do.
Copy to a local folder your app>code>core>Mage>Newsletter>Model>Subscriber.php. Navigate down to about line 311 & 313 and comment out using the two forward slashes the following commands:
1 if ($isConfirmNeed) {
//$this->sendConfirmationRequestEmail();
 } else {

//$this->sendConfirmationSuccessEmail();

}

This should stop the email sending.
Now what I propose is that you create a new php file on your root. Connect it up to Magento with the following code at the top.

require_once($_SERVER['DOCUMENT_ROOT'].'/shop/app/Mage.php');
Mage::app();

Note: My installation was in a “shop” folder.
Next we’ll need to use our model that we copied locally and perform the subscribe function. You can do this via the following method.
$_helper = new Mage_Newsletter_Model_Subscriber();
$_helper->subscribe("myemail@e-mail.co.uk");


This will subscribe that email as a guest to your newsletter list. Of course you can collect all of your email addresses in an array and run it through a foreach to add them all in one go.
The other way to do this would be to use the database connection. What I have is an array set up of emails such as:



$emails = array("myemail1@e-mail.co.uk","myemail2@e-mail.co.uk","myemail3@e-mail.co.uk");

I then use a simple foreach but this time instead of using the function I’ll use a simple mysql statement.
view source
print?
1foreach($emails as $email){
2 $db = Mage::getSingleton('core/resource')->getConnection('core/write');
3 $query "SELECT * FROM newsletter_subscriber WHERE subscriber_email = '$email'";
4 $result $db->query($query);
5 if($result->fetchAll()):
6 echo "Email Not Added: $email<br/>";
7 else:
8 $db->query("INSERT INTO newsletter_subscriber (`subscriber_id` , `store_id` , `change_status_at` , `customer_id` , `subscriber_email` , `subscriber_status` , `subscriber_confirm_code`) VALUES (NULL,'1',NULL,'0','$email','1',NULL)");
9 echo "Email Successfully Added: $email<br/>";
10 endif;
11}