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
Related
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');
Hi I have a custom Module built that sends an email when certain order statues are being created.
I have an observer that hooks into sales_order_place_after and my order object sinde observer.php is
public function getOrderStatus($observer)
{
$order = $observer->getEvent()->getOrder();
$status = $order->getStatus();
$enabled = Mage::getStoreConfig(self::XML_PATH_EMAIL_ENABLE);
if($enabled == 1){
if($status === "fraud")
{
$this->sendFraudEmail($observer);
}
}
}
but inside the transactional emails {{var order.increment_id}} is not working, even though in the observer I have : $order = $observer->getEvent()->getOrder();
what am I missing? Thanks.
Normally to send a custom transactional email you do something like the following;
$templateId = 16;
$sender = array(
'name' => Mage::getStoreConfig('trans_email/ident_support/name', Mage::app()->getStore()->getId()),
'email' => Mage::getStoreConfig('trans_email/ident_support/email', Mage::app()->getStore()->getId())
);
$vars = array('order' => $observer->getEvent()->getOrder());
Mage::getModel('core/email_template')->sendTransactional($templateId, $sender, $customerEmail, $customerName, $vars, $storeId);
I am using magento default shipment from the admin side.
so its working fine and sending email to the customers perfectly.
I want to create one script that can send email with the shipment details for all the completed orders in magento. This will be only for certain orders coming through CSV.
My script working fine when we are using the order_id of the processing orders but its not working for the completed orders . and not sending the Order items details in the email
please suggest me any solution for it..
Thanks a lot.
I am using the below script to do so :
function completeShipment($orderIncrementId,$shipmentTrackingNumber,$shipmentCarrierCode){
$shipmentCarrierTitle = $shipmentCarrierCode;
$customerEmailComments = '';
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
if (!$order->getId()) {
Mage::throwException("Order does not exist, for the Shipment process to complete");
}
try {
$shipment = Mage::getModel('sales/service_order', $order)->prepareShipment(_getItemQtys($order));
$arrTracking = array(
'carrier_code' => isset($shipmentCarrierCode) ? $shipmentCarrierCode : $order->getShippingCarrier()->getCarrierCode(),
'title' => isset($shipmentCarrierTitle) ? $shipmentCarrierTitle : $order->getShippingCarrier()->getConfigData('title'),
'number' => $shipmentTrackingNumber,
);
$track = Mage::getModel('sales/order_shipment_track')->addData($arrTracking);
$shipment->addTrack($track);
$shipment->register();
_saveShipment($shipment, $order, $customerEmailComments);
}catch (Exception $e) {
throw $e;
}
return $save;
}
function _getItemQtys(Mage_Sales_Model_Order $order){
$qty = array();
foreach ($order->getAllItems() as $_eachItem) {
if ($_eachItem->getParentItemId()) {
$qty[$_eachItem->getParentItemId()] = $_eachItem->getQtyOrdered();
} else {
$qty[$_eachItem->getId()] = $_eachItem->getQtyOrdered();
}
}
return $qty;
}
function _saveShipment(Mage_Sales_Model_Order_Shipment $shipment, Mage_Sales_Model_Order $order, $customerEmailComments = ''){
$shipment->getOrder()->setIsInProcess(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)->addObject($order)->save();
//$emailSentStatus = $shipment->getData('email_sent');
$ship_data = $shipment->getOrder()->getData();
$customerEmail = $ship_data['customer_email'];
$emailSentStatus = $ship_data['email_sent'];
if (!is_null($customerEmail)) {
$shipment->sendEmail(true, $customerEmailComments);
$shipment->setEmailSent(true);
}
return $this;
}
Thanks a lot dagfr...! the below code works for me to get done my task:
function completeShipment($orderIncrementId,$shipmentIncreamentId){
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
$ship_data = $order->getData();
$customerEmail = $ship_data['customer_email'];
$shipment = Mage::getModel('sales/order_shipment')->loadByIncrementId($shipmentIncreamentId);
$customerEmailComments = '';
$sent = 0;
if (!is_null($customerEmail)) {
$sent = $shipment->sendEmail(true, $customerEmailComments);
$shipment->setEmailSent(true);
}
return $sent;
}
Your script tries to create the shipment then send the email.
For completed orders the shipment is already created and you can't create it again, so your try fails before the email sending.
Just before :
try {
$shipment = Mage::getModel('sales/service_order', $order)->prepareShipment(_getItemQtys($order));
Check the status of the order, if it's complete, just need to get the shipment and send the mail
$shipment->sendEmail(true, $customerEmailComments);
$shipment->setEmailSent(true);
Else you can perform your script.
I found success using the order_shipment_api instead of the service_order model.
If you want to include the tracking number in the shipment email, make sure you add the tracking first and then use Mage::getModel('sales/order_shipment_api')->sendInfo($shipmentIncrementId).
Code Snippet:
$shipmentApi = Mage::getModel('sales/order_shipment_api');
//pass false for email, unless you want Magento to send the shipment email without any tracking info
//could also be written as $shipmentIncrementId = $shipmentApi->create($order->getIncrementId());
$shipmentIncrementId = $shipmentApi->create($order->getIncrementId(), array(), '' , false, 0);
//add tracking info ($shippingCarrier is case sensitive)
$shipmentApi->addTrack($shipmentIncrementId, $shippingCarrier, $shippingTitle, $trackingNumber);
//send shipment email with tracking info
$shipmentApi->sendInfo($shipmentIncrementId);
See app\code\core\Mage\Sales\Model\Order\Shipment\Api.php for all methods.
You can(should) also perform checks first:
//check for existing shipments if you want
if ($order->getShipmentsCollection()->count() == 0){
}
// and/or
if($order->canShip()){
}
I want to auto fill the shipping method automatically and not show it on the onepage checkout. I was able to hide the shipping method on my Onepagechekout by changing this on app/code/local/Mage/Checkout/controllers/OnepageController.php:
/**
* save checkout billing address
*/
public function saveBillingAction()
{
if ($this->_expireAjax()) {
return;
}
if ($this->getRequest()->isPost()) {
// $postData = $this->getRequest()->getPost('billing', array());
// $data = $this->_filterPostData($postData);
$data = $this->getRequest()->getPost('billing', array());
$customerAddressId = $this->getRequest()->getPost('billing_address_id', false);
if (isset($data['email'])) {
$data['email'] = trim($data['email']);
}
$result = $this->getOnepage()->saveBilling($data, $customerAddressId);
if (!isset($result['error'])) {
/* check quote for virtual */
if ($this->getOnepage()->getQuote()->isVirtual())
{
$result['goto_section'] = 'payment';
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
} elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1)
{
$result['goto_section'] = 'payment';
$result['update_section'] = array(
'name' => 'payment-method',
'html' => $this->_getPaymentMethodsHtml()
);
$result['allow_sections'] = array('shipping');
$result['duplicateBillingInfo'] = 'true';
} else {
$result['goto_section'] = 'shipping';
}
}
$this->saveShippingMethodAction();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
}
As you can see I changed the link where I redirect the next step after billing action to the payment step.
In order to auto-save a shipping method, I added
$this->saveShippingMethodAction();
at the end of the function, and this method looks like here:
public function saveShippingMethodAction()
{
$this->_expireAjax();
if ($this->getRequest()->isPost()) {
/* $this->savePaymentAction(); */
$data = $this->getRequest()->getPost('shipping_method', 'flatrate_flatrate');
$result = $this->getOnepage()->saveShippingMethod($data);
$this->getResponse()->setBody(Zend_Json::encode($result));
}
}
So what I did is try to include automatically flatrate_flatrate method as the default one.
But when I try to finish a sale, it says I didn't specify a shipping method. Any idea on why it doesn't work?
Now you need to force the shipping_method in the quote and in the session :
$forcedMethod = "your_method_code";
$this->getOnePage()->getQuote()
->getShippingAddress()
->setShippingMethod($forcedMethod)
->save();
Mage::getSingleton('checkout/session')->setShippingMethod($forcedMethod);
And just before you call :
$this->saveShippingMethodAction();
add a :
$this->getRequest()->setPost('shipping_method', $forcedMethod);
It should work ;)
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));
}
}