14

While creating an invoice programmatically, how can I make the system email the invoice to the customer?

$order=Mage::getModel('sales/order')->load($orderid); 
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
    Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
                   ->addObject($invoice)
                   ->addObject($invoice->getOrder());
$transactionSave->save();
12

After $transactionSave->save();:

$invoice->getOrder()->setIsInProcess(true);
$history = $invoice->getOrder()->addStatusHistoryComment(
    'Programmatically created invoice', true
);
$invoice->sendEmail(true, '');
$order->save();

This will instruct Magento to email the invoice to the customer.

  • is the set status is necessary for sending the email? – Qaisar Satti Apr 30 '15 at 9:57
  • Yes, this is a Magento norm. If not included, the order will not be set to Processing (which it should be once invoiced). – Moose Apr 30 '15 at 11:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.