Adding unsubscribe link in custom email magento - magento

How to add unsubscribe link in custom email notification i am sending an email through zend mail function i follow this function sending mail in magento in body part i want to add unsubscribe link how can we implement that?
In my e mail notification i am using this function.
public function sendMail()
{
$post = $this->getRequest()->getPost();
if ($post){
$random=rand(1234,2343);
$to_email = $this->getRequest()->getParam("email");
$to_name = 'Hello User';
$subject = ' Test Mail- CS';
$Body="Test Mail Code : ";
$sender_email = "sender#sender.com";
$sender_name = "sender name";
$mail = new Zend_Mail(); //class for mail
$mail->setBodyHtml($Body); //for sending message containing html code
$mail->setFrom($sender_email, $sender_name);
$mail->addTo($to_email, $to_name);
//$mail->addCc($cc, $ccname); //can set cc
//$mail->addBCc($bcc, $bccname); //can set bcc
$mail->setSubject($subject);
$msg ='';
try {
if($mail->send())
{
$msg = true;
}
}
catch(Exception $ex) {
$msg = false;
//die("Error sending mail to $to,$error_msg");
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($msg));
}
}

If you have a custom module use this code:
Mage::getModel('newsletter/subscriber')->loadByEmail($email)->getUnsubscriptionLink();
Explanation:
first part is the model for the subscriber.
If you want to see al the available methods within the model just use this code:
$myModel = Mage::getModel('newsletter/subscriber');
foreach (get_class_methods(get_class($myModel)) as $cMethod) {
echo '<li>' . $cMethod . '</li>';
}
the second part of the code loadByEmail($email) is to get 1 specific subscriber object. $email should be a string of the emailaddress.
The last part of the code is a selfexplaning method. It will generate a link to unsubscribe. This is a method that is given by Magento.

In my Magento version I get the following code by default when creating a new newsletter template:
Follow this link to unsubscribe <!-- This tag is for unsubscribe link -->{{var subscriber.getUnsubscriptionLink()}}
I expect it to work in any Magento version.

I am using Magento 1.9.
To add newsletter unsubscribe link in newsletter template here are following steps:
Override the core file
/app/code/core/Mage/Newsletter/Model/Subscriber.php
by copy in local directory
/app/code/local/Mage/Newsletter/Model/Subscriber.php
Open in editor to edit the code and seacrh the function sendConfirmationSuccessEmail()
replace the code
$email->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_SUCCESS_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_SUCCESS_EMAIL_IDENTITY),
$this->getEmail(),
$this->getName(),
array('subscriber'=>$this)
);
with this
$email->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_SUCCESS_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_SUCCESS_EMAIL_IDENTITY),
$this->getEmail(),
$this->getName(),
array('subscriber'=>$this, 'unsubscribe' =>$this->getUnsubscriptionLink())
);
and place this code in email template where you want to use unsubscribe link:
Unsubscribe here
That's it!
Hope this helps someone.

Related

How to send newsletter in Magento With dynamic content?

I am Extremely New to Magento.
I have created newsletter template with dummy content. Now I need to replace dummy content with dynamic content. Basically I need to send mail with new featured products in site. What should be my next step? .
How to do this please help me .
First you should create / override Newsletter module. I just suggest to send newsletter programmatic ally to customer
// This code returns all subscribers
$objCol=Mage::getResourceModel('newsletter/subscriber_collection')->load();
$collection = $objCol;
// Load the newsletter template model by $templateId
$tmplt=Mage::getModel('newsletter/template')->load($templateId);
$message=$tmplt->getTemplateText();
foreach($collection->getItems() as $item) {
$email = $item->getSubscriberEmail();
$name = $item->getSubscriberFullName();
try{
$mail = new Zend_Mail();
$mail->setFrom($tmplt->getTemplateSenderEmail());
$mail->setBodyHtml($message);
$mail->addTo($email, 'recipient');
$mail->setSubject($tmplt->getTemplateSubject());
$mail->send();
echo "Newsletter sent to ".$email."<br>";
} catch(Exception $e) {
echo $e->getMessage();
}
}
?>
May be help Magento custom emails

Magento OPC Observer redirect

I'm struggling with a special little problem related to the redirect out of some Magento observer.
I wrote an extension and put an observer to the "checkout_submit_all_after" event, which works out just fine. My little extension automatically creates an invoice and sets the order status to processing, once the payment method is "Invoice". Unfortunately the redirect after submitting an order in the one page checkout doesn't work anymore. It always redirects to "checkout/cart" instead of "checkout/onepage/success".
Someone any ideas what I'm doing wrong?
Here's my code:
class Shostra_AutoInvoice_Model_Order_Observer
{
public function __construct()
{
}
public function auto_create_invoice($observer)
{
$order = $observer->getEvent()->getOrder();
if (!$order->hasInvoices()) {
$payment = $order->getPayment()->getMethodInstance()->getTitle();
Mage::log("payment method: " . $payment);
if($payment=="Rechnung"){
Mage::log("autocreating invoice");
$invoice = $order->prepareInvoice();
$invoice->register();
$invoice->pay();
$invoice->save();
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
Mage::log("invoice created and saved");
}
$this->addComment('Order automatically set to paid.');
} else {
$this->addComment('no invoices found.');
}
$response = $observer->getResponse();
$response->setRedirect(Mage::getUrl('checkout/onepage/success'));
Mage::getSingleton('checkout/session')->setNoCartRedirect(true);
}
}
Thanks a lot!
Why don't you try sales_order_save_after event and try saving it, so no issues with redirection manually as Magento will take its own course,
you can refer to this link for more explanation
http://inchoo.net/magento/magento-orders/automatically-invoice-ship-complete-order-in-magento/

Magento custom controller action does not render design

people. i have a problem. I have an action in my custom module, that creates customer.
There is a code:
class SeosClub_BusinessCategory_CustomerController extends Mage_Core_Controller_Front_Action {
public function createAction(){
$requestData = Mage::app()->getRequest()->getParams();
if(!$requestData['id'] || !$requestData['activation_code']){
Mage::getSingleton('core/session')->addError('Request data invalid');
}
$company = Mage::getModel('businesscategory/company')->load($requestData['id']);
if (!$company->getId()){
Mage::getSingleton('core/session')->addError('Your company does not exist');
}
if($company->getCustomerId()){
Mage::getSingleton('core/session')->addNotice($this->__('Customer already created. Forgot password?'));
$this->_redirect('customer/account/forgotpassword/');
return;
}
$group = Mage::getModel('customer/group')->load('Companies', 'customer_group_code');;
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->setStore(Mage::app()->getStore());
$customer->setData('group_id', $group->getId());
$customer->setFirstname($company->getName());
$customer->setLastname($this->__('Unknown'));
$customer->setEmail($company->getEmail());
$customer->setPassword(Mage::helper('core')->getRandomString(8));
try{
$customer->save();
$customer->sendNewAccountEmail();
$company->setCustomerId($customer->getId());
$company->save();
Mage::getSingleton('core/session')->addSuccess($this->__('Account was created succefully'));
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError($e->getMessage());
}
$this->loadLayout();
$this->renderLayout();
}
}
I have also installed theme on my magento. But, when i open the page, it renderes base magento theme, not my installed theme.
If i comment code from if($company->getCustomerId()) to $this->loadLayout(); (not including $this->loadLayout();), it renderes correct theme.
Any ideas?
Enable developer mode in magento. Uncomment display_errors in index.php. You should see some errors, since you have:
$company = Mage::getModel('businesscategory/company')->load($requestData['id']);
$requestData['id'] might not be set here, because your if condition is not ending the processing of the method. So further in the code you might not have $company and you call functions on null.
Check if $company is an object.
I think it renders the default theme becuse you have errors.
Ok, to fix that i needed to send customer email after rendering layout.

sending email to all newsletter members with codeigniter

I want to send an email using codeigniter library to my newsletter members and I want to mention each members' Email address in email's content. For doing that, I used foreach loop to send the email one by one. The problem is that the code sends email to just one member ( the first member ) of my newsletter. I've checked my code which gets members from the database and it printed out all the members.
This is my model:
function send_news()
{
$subscribers = $this->get_subscriber_data();
foreach($subscribers as $subscriber)
{
$this->load->helper('typography');
//Format email content using an HTML file
$data['news_Title'] = $this->input->post('news_Title');
$HTML_Message = $this->load->view('admin/includes/newsletter_html_format', $data, true);
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from('newsletter#site.com', 'newsletter of site.com');
$this->email->to($subscriber->subscriber_Email);
$this->email->subject('newsletter of site.com');
$this->email->message($HTML_Message);
return $this->email->send();
}
}
and this is how I'm getting subscribers list:
function get_subscriber_data($options = array())
{
$query = $this->db->get('mg_newsletter');
if(isset($options['subscriber_Id']))
return $query->row(0);
return $query->result();
}
when I try to echo $subscriber->subscriber_Email it prints all the emails in the database one after another. but it does not send email to all of them. What am I doing wrong?!
use
$this->email->clear()
As codeignitor says:
Initializes all the email variables to an empty state. This function is intended for use if you run the email sending function in a loop, permitting the data to be reset between cycles.
foreach ($list as $name => $address)
{
$this->email->clear();
$this->email->to($address);
$this->email->from('your#example.com');
$this->email->subject('Here is your info '.$name);
$this->email->message('Hi '.$name.' Here is the info you requested.');
$this->email->send();
}
If you set the parameter to TRUE any attachments will be cleared as well. Then let us know
You are "return" -ing inside your loop, which exits the function.
Just send
You can keep the loading helper file and email configuration outside the loop and then remove the return from for loop, it will send to all subscribers one by one and then after loop finishes you can do the return statement.

magento pass variable from controller to another model

I want to send custom mail through smtp.For which I installed http://www.magentocommerce.com/magento-connect/aschroder-com-smtp-pro-email-free-and-easy-magento-emailing-for-smtp-gmail-or-google-apps-email.html.
Which works properly for every mail provided by magento as default.
Now since the admin is having mail Id of google apps , my custom mail is not received by admin.So for this reason I want to Integrate my controller with the sending mail function of ashrodder extension.
My Controller code:
$frm = 'mail#domainname.com';
$to = 'admin#domainname.com';
$subject = "UPDATE";
$mail = new Zend_Mail('utf-8');
$mail->setBodyHtml($message)
->setFrom($frm, 'Admin')
->addTo($to, 'Site Admin')
->setSubject($subject);
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Mail sent successfully.');
}
catch(Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send email.');
}
My question is simple : How should I pass [to,from,body] variable to any other model/controller ?
Please Help .Thanks in Advance
I think overriding the extensions controller would be the best solution.Check this link How to extend a controller

Resources