sending mail in magento - 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));
}
}

Related

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;
}
}

resetting password in codeigniter

i'm new to codeigniter, and i am attempting to create a password reset system
this is my controller:
public function changePassword(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
$data['title'] = 'Change my Password | Watch Stop';
$this->load->view('template/header', $data);
$this->load->view('watch_stop/vpassword', $data);
$this->load->view('template/footer');
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function reset_password(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
//validating form
$this->form_validation->set_rules('old_password','Old Password','trim|required|min_length[5]|md5');
$this->form_validation->set_rules('new_password','New Password','trim|required|min_length[5]|matches[cnew_password]|md5');
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
if ($this->form_validation->run() == FALSE)
{
$this->changePassword();
//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Failed to update password</div>');
}else {
$query=$this->customer_model->change_password();
$data = array( "main_content" => 'includes/memberadmin/memberadmin_cpass_process',
"query" => $query
);
$this->load->view('includes/memberadmin/template',$data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
this is my model:
function change_password(){
$this->db->select('id');
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('password',$this->input->post('old_password'));
$query=$this->db->get('user');
if ($query->num_rows() > 0)
{
$row = $query->row();
if($row->email===$this->session->userdata('email'))
{
$data = array(
'new_password' => $this->input->post('new_password')
);
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('new_password',$this->input->post('old_password'));
if($this->db->update('user', $data))
{
return "Password Changed Successfully";
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Wrong Old Password";
}
}
When i click on the update button in my reset password page, i am getting the following error for my new password confirmation field: Unable to access an error message corresponding to your field name Confirm Password.()
please help!
1) there are two pipe signs near required||md5
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
change it to
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required|md5');
2) changing input to md5 at this stage is not good.
You have to use password_hash function.
Read More >> http://php.net/manual/en/function.password-hash.php
3) You forgot to load model. $this->load->model('customer_model');

Laravel4 Doesnt show old::input()

New to laravel4 and cant get the basic things to work such as:
function doRegister() {
try {
$email = Input::get('email');
$type = Input::get('type'); // <-- Data from radio button
# Check if email exists
if ( User::where('email','=',$email)->count() > 0 ) {
# This account already exists
throw new Exception( 'This email already in use by someone else.' );
}
} catch (Exception $e) {
return Redirect::to('/')->withInput()->with('message', $e->getMessage() );
}
}
Now on the homepage controller (which is /) I cant read the value of Input::old('type');
and it returns empty. How come?
Try this instead:
function doRegister()
{
$rules = array('email' => 'required|email|unique:users');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('/')->withInput()>withErrors($validator);
}
else {
$email = Input::get('email');
$type = Input::get('type');
// Register...
}
}
You can retrieve validation errors using:
$errors->first('email');

Prevent subscriber saving in observer newsletter_subscriber_save_before Magento

I created an Observer to monitor the event subscriber_save_before. In this observer I handle a new field, the value of that is saved, but if some errors occurs I wanna the record not to be saved and to display only my error message. The throwException seems not to do the trick. The only method I think could work is to force the email field to null but wasn't able to achieve this.
In the subscriberController.php (Mage Core) I have this:
$email = (string) $this->getRequest()->getPost('email');
try {
if (!Zend_Validate::is($email, 'EmailAddress')) {
Mage::throwException($this->__('Please enter a valid email address.'));
}
This is my code (not working):
public function NewsletterSaveSubscriber($observer)
{
$subscriber = $observer->getEvent()->getSubscriber();
$name = Mage::app()->getRequest()->getParam('subscriber_name');
// server side validation
// no name specified
if (!Zend_Validate::is(trim($name), 'NotEmpty')) {
$session = Mage::getSingleton('core/session');
try {
Mage::throwException(Mage::helper('newsletter')->__('The name field cannot be empty!'));
} catch (Mage_Core_Exception $e) {
$session->addException($e, Mage::helper('newsletter')->__('There was a problem: %s', $e->getMessage()));
}
$observer->getRequest()->setPost('email', ''); // this code doesn't work
Mage::app()->getRequest()->setPost('email', ''); // this too
// Ohh nooo! The subscriber is stored :-(
return $this;
}
// save the name
$name = htmlspecialchars($name);
$subscriber->setSubscriberName($name);
return $this;
}
This will solve your probem:
//Error Message
$session = Mage::getSingleton('core/session');
$session->getMessages(true);
$session->addError(Mage::helper('cartware_automaticreview')->__('CouldĀ“t save.'));
// Ohh nooo! The subscriber is not stored :)
$controller = $observer->getControllerAction()->setFlag('',Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH,true);
$controller->getResponse()->setRedirect(Mage::app()->getRequest()->getServer('HTTP_REFERER'));
return;
Good luck!

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