Custom email sending in magento custom module - magento

I am working on a module that will send an email after 7 days of order completion. I'm stuck on sending emails. I can see the email template in transactional emails drop down in admin. But the email is not being sent.
Here is my confix.xml part for including email template.
<template>
<email>
<recurring_order_email_template translate="label">
<label>Recurring order email</label>
<file>coeus_recurring_order_email.html</file>
<type>html</type>
</recurring_order_email_template>
</email>
</template>
and this is how I am sending email in controller action
$emailTemplate = Mage::getModel('core/email_template')
->loadDefault('coeus_recurring_order_email');
$emailTemplateVariables = array();
$emailTemplateVariables['var1'] = 'var1 value';
$emailTemplateVariables['var2'] = 'var 2 value';
$emailTemplateVariables['var3'] = 'var 3 value';
$emailTemplate->getProcessedTemplate($emailTemplateVariables);
$emailTemplate->setSenderName('sender name');
$emailTemplate->setSenderEmail('sender#test.com');
try {
$emailTemplate->send('myemail#gmail.com', 'bla bla',$emailTemplateVariables);
} catch (Exception $e) {
echo $e->getMessage();
}
I don't know why its not working.

$emailTemplate = Mage::getModel('core/email_template')->loadDefault('recurring_order_email_template');
//Getting the Store E-Mail Sender Name.
$senderName = Mage::getStoreConfig('trans_email/ident_general/name');
//Getting the Store General E-Mail.
$senderEmail = Mage::getStoreConfig('trans_email/ident_general/email');
//Variables for Confirmation Mail.
$emailTemplateVariables = array();
$emailTemplateVariables['name'] = $customerName;
$emailTemplateVariables['email'] = $customerEmail;
//Appending the Custom Variables to Template.
$processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
//Sending E-Mail to Customers.
$mail = Mage::getModel('core/email')
->setToName($senderName)
->setToEmail($customerEmail)
->setBody($processedTemplate)
->setSubject('Subject :')
->setFromEmail($senderEmail)
->setFromName($senderName)
->setType('html');
try{
//Confimation E-Mail Send
$mail->send();
}
catch(Exception $error)
{
Mage::getSingleton('core/session')->addError($error->getMessage());
return false;
}

Change your etc/config.xml code to below:
<template>
<email>
<recurring_order_email_template>
<label>Recurring order email</label>
<file>coeus_recurring_order_email.html</file>
<type>html</type>
</recurring_order_email_template>
</email>
</template>
Change your controller code to below:
$emailTemplate = Mage::getModel('core/email_template')
->loadDefault('recurring_order_email_template');
$emailTemplateVariables = array();
$emailTemplateVariables['var1'] = 'var1 value';
$emailTemplateVariables['var2'] = 'var 2 value';
$emailTemplateVariables['var3'] = 'var 3 value';
$emailTemplate->getProcessedTemplate($emailTemplateVariables);
$emailTemplate->setSenderName('sender name');
$emailTemplate->setSenderEmail('sender#test.com');
try {
$emailTemplate->send($recipientEmail, $senderName, $emailTemplateVariables);
} catch (Exception $e) {
echo $e->getMessage();
}
Change your $recipientEmail, $senderName & $emailTemplateVariables as per your need.
To load a email template, you must specifiy the tag name after
<template>
<email>
</email>
</template>
that you provided in the config.xml

I think you made a mistake here.
$emailTemplate = Mage::getModel('core/email_template')->loadDefault('coeus_recurring_order_email');
try this
$emailTemplate = Mage::getModel('core/email_template')
->loadDefault('recurring_order_email_template');
to load a email template you have to give the tag name that you provide in the config.xml
eg: in you code
use
<recurring_order_email_template>
to load email template

Related

How to reset Password Using PHP Codeigniter

Am working on a Password reset system whereby the user who forgot his password can request for password reset link by submitting his email used in registration. I successfully create the email, it sent the link and I test the link by clicking on it. The link went through and load the reset page but my problem is how to make the system recognise the user who click through and get all the details including Name, Token, email with which the system will confirm that the user is the user who requested the link.
The following is what I have done so far:
Controller
public function preset(){
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_error_delimiters("<div class='alert alert-warning'><span type='button' class='close' data-dismiss='alert'>&times</span>","</div>");
if($this->form_validation->run() == false){
$this->load->view('passwordrecovery.php', $data);
}
else{
$eMail = $this->input->post('email');
$this->db->where("email = '$eMail'");
$this->db->from("useraccount");
$countResult = $this->db->count_all_results();
if($countResult >=1){
// $data['firstName'] = '';
// $data['lastName'] = '';
$this->db->where("email = '$eMail'");
$getUserData =$this->db->get("useraccount")->result();
foreach($getUserData as $userD){
$data['firstName'] = $userD->firstname;
$data['lastName'] = $userD->lastname;
}
$sender_email = 'xxx#gmail.com';
$user_password = 'xxxxxx';
$token = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 50);
$subject = 'Password Reset';
$message = '';
$message .= "<h2>You are receiving this message in response to your request for password reset</h2>"
. "<p>Follow this link to reset your password <a href='".site_url()."/authenticate/resetpassword/.$token' >Reset Password</a> </p>"
. "<p>If You did not make this request kindly ignore!</p>"
. "<P class='pj'><h2>Kind Regard: Votemate</h2></p>"
. "<style>"
. ".pj{"
. "color:green;"
. "}"
. "</style>"
. "";
// Configure email library
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = $sender_email;
$config['smtp_pass'] = $user_password;
$config['mailtype'] = 'html';
// Load email library and passing configured values to email library
$this->load->library('email', $config);
//$this->email->set_newline("rn");
$this->email->set_mailtype("html");
// Sender email address
$this->email->from($sender_email);
// Receiver email address
$this->email->to($eMail);
// Subject of email
$this->email->subject($subject);
// Message in email
$this->email->message($message);
if ($this->email->send()) {
$eMail = $this->input->post('email');
$ipadd = $this->input->ip_address();
$insert = array(
'email' => $eMail,
'ipaddress' => $ipadd,
'token' => $token
);
$this->db->insert('passwordreset', $insert);
$mail = $this->session->set_userdata('email');
$data['success'] = 'Email Successfully Send !';
$this->load->view('linksent.php', $data);
} else {
$data['error'] = '<p class="error_msg">Invalid Gmail Account or Password !
</p>';
}
$this->load->view('passwordrecovery.php', $data);
}
if($countResult <= 0){
//user already registered
$data['error'] = "<div class='alert alert-warning'> Invalid
email address<span type='button' class='close' data-
dismiss='alert'>&times</span></div>";
$this->load->view('passwordrecovery.php',$data);
}
}
}
View
<div>
<h1>Password Recovery</h1>
<h3>Enter your email to receive the password reset link in
your Inbox</h3>
<br/>
<?php echo form_open('authenticate/preset');?>
<?php echo $error;?>
<div class="form-group">
<input type="text" name="email" required="required">
</div>
<div class="form-group">
<input type="submit" value="Send" class="btn-success
btn" >
</div>
<?php echo form_close()?>
<br/><br/><br/>
</div>
Database: The following is database where I store the info:
CREATE TABLE `passwordreset` (
`resetid` int(11) NOT NULL,
`email` varchar(150) NOT NULL,
`ipaddress` varchar(25) NOT NULL,
`token` varchar(512) NOT NULL
) ENGINE
The help I need is how to get the details (Name, email, token) of the user who click the link from his email and use it to validate and also use it to update his password. Thanks
pass user email or token in url or in hidden field when user click on verify link and check in controller method.
<a href="<?=site_url('user_verification?user_email=' . $user_email . '&user_code=' . $user_code);?> Click To Verifiy Email </a>
user_verification controller
public function user_verification_get()
{
$user_email = $this->input->get('user_email');
$user_code = $this->input->get('user_code');
$data=$this->admin_model->user_verification($user_email,$user_code);
if($data)
{
$data['message'] = 'Success.';
}
else
{
$data['message'] = 'Not Valid User.';
}
$this->load->template('verify', $data);
}
Model
public function user_verification($user_email,$user_code){
$this->db->select('user_email');
$this->db->where('user_email',$user_email);
$this->db->where('user_code',$user_code);
$query = $this->db->get('users');
if($query->row_array() > 0)
{
$data['user_isactive'] = true;
$this->db->where('user_email',$user_email);
$this->db->update('users',$data);
return $query->row_array();
}
return false;
}
You have to create a database table to store the tokens. Before sending the email, You must generate a unique token and add it into a separate table. The password reset link must contain encoded token and userID. Once the password reset link is clicked, you must check the encoded token and UserID in the link matches to the entry in database? If yes, then show the change password page, If not, you must show a message "Link is expired" or whatever.
Here is the hint of code from my project.
$act_code = md5(rand(0,1000).'uniquefrasehere');
$activate['UserID'] $USERID;
$activate['TokenNumber'] = $act_code;
$activate['UserEmail'] = $email;
$activate['TokenTime'] = time();
$str_tmp = $this->db->insert_string('forgetpasswordtoken', $activate);
$query_tmp = $this->db->query($str_tmp);
Once the link is clicked, You must check using the following code:
$record = $this->user_model->checkforgot($uid[0], base64_decode($uid[1]));
if($record == true){
$data['uid'] = $uid[1];
}
else
{
$msg = "You have already changed your password or your link was expired.!";
}
And What the checkforgotpassword function does? Here is below:
function checkforgot($token, $id)
{
$qry = $this->db->query("SELECT * FROM forgetpasswordtoken WHERE TokenNumber = '".$token."' AND UserID = $id");
$num_row = $qry->num_rows();
if($num_row!=0)
{
$del = $this->db->delete('forgetpasswordtoken', array('TokenNumber' => $token, 'UserID' => $id));
return true;
}
else
{
return false;
}
}
You can further add the time limit of few hours before the link expires.
Let me know after adding this in your project.
Thanks,

ReCaptcha For Newbies

I've got ReCaptcha working but despite reading the documentation and the answers posted here, I'm still at a loss for setting up the server side. My HTML form calls <form id="contactForm" class="well" method="POST" action="php/contactform.php">.
What and where do I place the server-side recaptcha in this file? (I meant it when I titled this newbie. I really need explicit instructions):
<?php
if($_POST){
// response hash
$response = array('message'=>'');
}
try {
// Get values from form
$name=$_POST['cname'];
$email=$_POST['cemail'];
$subject=$_POST['csubject'];
$message=$_POST['cmessage'];
$formcontent="From: $name \n Email: $email \n Subject: $subject \n: $message";
$recipient = "rabbidubrow#fivegates.org";
$subject = "KHF Contact Form";
$mailheader = "From: $email \r\n";
$send_contact=mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
// let's assume everything is ok, setup successful response
$response['type'] = 'success';
$response['message'] = 'Thank you! We will be in touch shortly.';
} catch(Exception $e){
$response['type'] = 'error';
$response['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($response);
exit;
?>
You will need
1. Include your recaptcha.php
2. Declare your private and public keys
3. Check for POST of your captcha. If it success, give a response, if it fails, catch the exception.
Below is one of my scripts that was done up for your reference.
require_once('assets/config/recaptchalib.php');
$publickey = "xxxx";
$privatekey = "xxxxx";
if ($_POST["recaptcha_response_field"]) {
$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$continue = true;
}
}

Send invoice email to custom mail address in magento

I have added custom functionality to send invoice email to some other mail address(excluding customer & admin). For this I have called custom function in observers
<sales_order_invoice_save_after>
<observers>
<test>
<type>singleton</type>
<class>test/observer</class>
<method>sentMailToothers</method>
</test>
</observers>
Observer code
$template_id = 'sales_email_invoice_template';
$emailTemplate = Mage::getModel('core/email_template')->loadDefault($template_id);
$storeId = Mage::app()->getStore()->getStoreId();
$invoice = $observer->getEvent()->getInvoice();
$order = $observer->getEvent()->getInvoice()->getOrder();
if ($order->hasInvoices())
{
foreach ($order->getInvoiceCollection() as $inv)
{
$paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())->setIsSecureMode(true);
$paymentBlockHtml = $paymentBlock->toHtml();
$email_to = 'test#test.com';//dynamic email address
$customer_name = 'Test'
$email_template_variables = array(
'order' => $order,
'invoice' => $invoice,
'payment_html' => $paymentBlockHtml
);
$sender_name = Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_STORE_STORE_NAME);
$sender_email = Mage::getStoreConfig('trans_email/ident_general/email');
$emailTemplate->setSenderName($sender_name);
$emailTemplate->setSenderEmail($sender_email);
$processedTemplate = $emailTemplate->getProcessedTemplate($email_template_variables);
echo $processedTemplate;die;
//Send the email!
$emailTemplate->send($email_to, $customer_name, $email_template_variables);
}
}
Everything works fine except , product information not showing in templates.
Can somebody figure out what I am doing wrong?
No need this code. In magento have default functionality for sending invoice email to Bcc.
Goto Admin->System(main nav)->configuration(sub nav)->Sales emails->invoice(tab)-> field "Send Invoice Email Copy To" .
please check below screenshots.

sending mail in magento

How to send email in magento writing an action in index controller?
my index controller;
public function postAction()
{
$post = $this->getRequest()->getPost();
if(!$post) exit;
$translate = Mage::getSingleton('core/translate');
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Please enter a valid email address. For example johndoe#domain.com.').'</div>';
exit;
}
$storeId = Mage::app()->getStore()->getStoreId();
$emailId = Mage::getStoreConfig(self::XML_PATH_SAMPLE_EMAIL_TEMPLATE);
$mailTemplate = Mage::getModel('core/email_template');
$mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId))
->setReplyTo($post['email'])
->sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null)
if (!$mailTemplate->getSentSuccess()) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').'</div>';
exit;
}
$translate->setTranslateInline(true);
echo '<div class="success-msg">'.Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.').'</div>';
}
catch (Exception $e) {
$translate->setTranslateInline(true);
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').$e.'</div>';
exit;
}
}
is there any wrong..
please help me to out of this..
Thanks in advance..
Here's another way, if you don't need templates.
Call from a controller.
<?php
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('John Customer');
$mail->setToEmail('customer#email.com');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('yourstore#url.com');
$mail->setFromName("Your Name");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
$this->_redirect('');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
It looks like there are a few problems with the way you are calling sendTransactional(). First off, $templateId is not defined, it looks like you've actually stored the template id in $emailId. Also, $sender, $email, and $name are undefined. You can try something like this:
->sendTransactional($emailId, 'general', $post['email'], "Need a send to name here")
This is only going to work if you are getting a valid template id back from your call to getStoreConfig(). You'll also need to set the last name param correctly.
There could be other issues, but that's what I noticed with a quick glance anyway.
Finally i created a function for sending mail by using zend
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));
}
}

Magento - problem sending email through an action

I have a basic module that accepts form data on the frontend and saves to a database.
What I'm also looking to do is to send an email if the data has been saved successfully.
I'd like the email to be sent to the store owner:
I have done the following to try and get this to work:
app/code/local/Aero/Catalogrequest/etc/config.xml
<template>
<email>
<request_brochure_email translate="label" module="Aero_Catalogrequest">
<label>Request a brochure</label>
<file>request_brochure.html</file>
<type>html</type>
</request_brochure_email>
</email>
</template>
and
<default>
<Aero_Catalogrequest>
<sendemail>
<template>request_brochure_email</template>
</sendemail>
</Aero_Catalogrequest>
</default>
I have created a template file in: app/locale/en_US/template/email/request_brochure.html
<p>
{{var data.fname}}
</p>
And this is my postAction in my IndexController.php
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$request = Mage::getModel('catalogrequest/catalogrequest');
$data = $this->getRequest()->getPost();
$data['time_added'] = now();
$data['country'] = $data['country_id'];
$data['ip'] = $_SERVER['REMOTE_ADDR'];
$data['fname'] = ucwords($data['fname']);
$data['lname'] = ucwords($data['lname']);
$data['address1'] = ucwords(str_replace(",", " ",$data['address1']));
$data['address2'] = ucwords(str_replace(",", " ",$data['address2']));
$data['city'] = ucwords($data['city']);
if(empty($data['region'])){
$data['state'] = Mage::getModel('directory/region')->load($data['state'])->getCode();
} else {
$data['state'] = $data['region'];
}
$postObject = new Varien_Object();
$postObject->setData($post);
// Validate
if(!$errors = $request->validate($data)){
MAGE::getSingleton('core/session')->addError($errors);
}
// Add to database
try {
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_SAMPLE_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $data)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$request->setData($data)->save();
MAGE::getSingleton('core/session')->addSuccess($this->__('<h2>Thank you</h3> You can expect to receive your catalogue in 10-14 days.o. '));
$translate->setTranslateInline(true);
$this->_redirect('*/*/thanks');
} catch(Exception $e){
MAGE::getSingleton('core/session')->addError('Sorry, we\'ve had some trouble saving your request');
$this->_redirect('*/*/');
return;
}
}
return;
}
When submitting my form, data isn't sent to the email address that I have configured in the admin
Does anyone have any idea what I'm doing wrong?
Thanks
I think you need to set a subject, otherwise you won't pass:
public function isValidForSend()
{
return !Mage::getStoreConfigFlag('system/smtp/disable')
&& $this->getSenderName()
&& $this->getSenderEmail()
&& $this->getTemplateSubject();
}
(Mage_Core_Model_Email_Template)
So, in your email template, add: <!--#subject The subject of email #-->
Hope that helps
Ok, so to make it work, I had to replace:
array('data' => $data)
with
array('data' => $postObject)
All sends perfectly now!
Thanks all

Resources