Send an invoice by email

@param  int    $iInvoiceId     The ID of the invoice to send
@param  string $sEmailOverride Send to this email instead of the email defined by the invoice object

@return bool
550806
public function send(int $iInvoiceId, string $sEmailOverride = null): bool
    {
        try {

            $oInvoice = $this->getById($iInvoiceId);

            if (empty($oInvoice)) {
                throw new InvoiceException('Invalid Invoice ID', 1);
            }

            if ($oInvoice->state->id !== self::STATE_OPEN) {
                throw new InvoiceException('Invoice must be in an open state to send.', 1);
            }

            if (!empty($sEmailOverride)) {

                //  @todo, validate email address (or addresses if an array)
                $aEmails = explode(',', $sEmailOverride);

            } elseif (!empty($oInvoice->customer->billing_email)) {

                $aEmails = explode(',', $oInvoice->customer->billing_email);

            } elseif (!empty($oInvoice->customer->email)) {

                $aEmails = [$oInvoice->customer->email];

            } elseif (!empty($oInvoice->email)) {

                $aEmails = [$oInvoice->email];

            } else {
                throw new InvoiceException('No email address to send the invoice to', 1);
            }

            $oEmailer           = Factory::service('Emailer', 'nails/module-email');
            $oInvoiceEmailModel = Factory::model('InvoiceEmail', 'nails/module-invoice');

            $oEmail       = new \stdClass();
            $oEmail->type = 'send_invoice';
            $oEmail->data = [
                'invoice' => $oInvoice,
            ];

            foreach ($aEmails as $sEmail) {

                $oEmail->to_email = $sEmail;

                $oResult = $oEmailer->send($oEmail);

                if (!empty($oResult)) {

                    $oInvoiceEmailModel->create(
                        [
                            'invoice_id' => $oInvoice->id,
                            'email_id'   => $oResult->id,
                            'email_type' => $oEmail->type,
                            'recipient'  => $oEmail->to_email,
                        ]
                    );

                } else {
                    throw new InvoiceException($oEmailer->lastError(), 1);
                }
            }

        } catch (\Exception $e) {
            $this->setError($e->getMessage());
            return false;
        }

        return true;
    }
950373
public function send($override = false)
	{
		if ($this->sent && !$override)
		{
			throw new ResponseAlreadySentException('Response has already been sent');
		}

		// Call trigger
		$dispatcher = EventManager::dispatcher("onResponseSend");
		if( !$dispatcher->isRun() )
		{
			// fixed json
			$dispatcher->dispatch(new ResponseSendEvent($this));
		}

		// Send our response data
		$this->sendHeaders();
		$this->sendBody();

		// Lock the response from further modification
		$this->lock();

		// Mark as sent
		$this->sent = true;

		// If there running FPM, tell the process manager to finish the server request/response handling
		if (function_exists('fastcgi_finish_request'))
		{
			fastcgi_finish_request();
		}

		$dispatcher->complete();

		return $this;
	}
1342560
public function SendOrderNotification($sSendToMail = null, $sSendToName = null)
    {
        $bOrderSend = false;

        if (is_null($sSendToMail)) {
            $sSendToMail = $this->fieldUserEmail;
        }
        if (is_null($sSendToName)) {
            $sSendToName = $this->fieldAdrBillingFirstname.' '.$this->fieldAdrBillingLastname;
        }

        $oMail = $this->GetOrderNotificationEmailProfile(self::MAIL_CONFIRM_ORDER);

        TCMSImage::ForceNonSSLURLs(true); // force image urls to non ssl for use in order email
        if (is_null($oMail)) {
            $bOrderSend = TGlobal::Translate('chameleon_system_shop.order_notification.error_mail_template_not_found', array('%emailTemplate%' => self::MAIL_CONFIRM_ORDER));
        } else {
            $aMailData = $this->sqlData;
            $aMailData = $this->AddOrderNotificationEmailData($aMailData);
            $aMailData = $this->AddOrderNotificationEmailComplexData($aMailData);
            $oMail->AddDataArray($aMailData);
            $aOrderDetails = $this->GetSQLWithTablePrefix();
            $oMail->AddDataArray($aOrderDetails);
            $oMail->ChangeToAddress($sSendToMail, $sSendToName);
            $bOrderSend = $oMail->SendUsingObjectView('emails', 'Customer');
            $this->SaveOrderNotificationDataToOrder($bOrderSend, $oMail, $sSendToMail);
        }
        TCMSImage::ForceNonSSLURLs(false); // reset - force non ssl urls

        return $bOrderSend;
    }
813132
private function sendEmail(OutputInterface $output, $content)
    {
        $output->writeln("Sending an email");
        $transport = $this->getTransport();
        $mailer    = \Swift_Mailer::newInstance($transport);

        $message = \Swift_Message::newInstance('Bldr Notify - New Message')
            ->setFrom(['no-reply@bldr.io' => 'Bldr'])
            ->setTo($this->getEmails())
            ->setBody(
                "<p>Bldr has a new message for you from the most recent build</p>\n<br /><pre>{$content}</pre>\n",
                "text/html"
            )
            ->addPart($content, 'text/plain')
        ;

        $result = $mailer->send($message);

        return $result;
    }
803950
protected function updateLineItems(int $iInvoiceId, array $aItems): void
    {
        $oItemModel  = Factory::model('InvoiceItem', 'nails/module-invoice');
        $aTouchedIds = [];

        //  Update/insert all known items
        foreach ($aItems as $aItem) {

            $aData = [
                'label'         => getFromArray('label', $aItem, null),
                'body'          => getFromArray('body', $aItem, null),
                'order'         => getFromArray('order', $aItem, 0),
                'currency'      => getFromArray('currency', $aItem, null),
                'unit'          => getFromArray('unit', $aItem, null),
                'tax_id'        => getFromArray('tax_id', $aItem, null),
                'quantity'      => getFromArray('quantity', $aItem, 1),
                'unit_cost'     => getFromArray('unit_cost', $aItem, 0),
                'sub_total'     => getFromArray('sub_total', $aItem, 0),
                'tax_total'     => getFromArray('tax_total', $aItem, 0),
                'grand_total'   => getFromArray('grand_total', $aItem, 0),
                'callback_data' => getFromArray('callback_data', $aItem, null),
            ];

            //  Ensure callback data is encoded as JSON
            if (array_key_exists('callback_data', $aData)) {
                $aData['callback_data'] = json_encode($aData['callback_data']);
            }

            if (!empty($aItem['id'])) {

                //  Update
                if (!$oItemModel->update($aItem['id'], $aData)) {
                    throw new InvoiceException('Failed to update invoice item.', 1);
                } else {
                    $aTouchedIds[] = $aItem['id'];
                }

            } else {

                //  Insert
                $aData['invoice_id'] = $iInvoiceId;
                $iItemId             = $oItemModel->create($aData);

                if (!$iItemId) {
                    throw new InvoiceException('Failed to create invoice item.', 1);
                } else {
                    $aTouchedIds[] = $iItemId;
                }
            }
        }

        //  Delete those we no longer require
        if (!empty($aTouchedIds)) {

            $oDb = Factory::service('Database');
            $oDb->where_not_in('id', $aTouchedIds);
            $oDb->where('invoice_id', $iInvoiceId);
            if (!$oDb->delete($oItemModel->getTableName())) {
                throw new InvoiceException('Failed to delete old invoice items.', 1);
            }
        }
    }
1168138
public function sendByType(int $typeId, string $msg, ?string $dest = null, bool $flush = false) : void
    {
        $msg = $this->composeMsg($msg, $dest);

        $subscriptions = $this->subscriptionTable->findAll()
            ->where('subscription.active', 1)
            ->where('user.active', 1)
            ->where('user:user_subscription_type.subscription_type_id', $typeId);

        foreach ($subscriptions as $row)
        {
            $this->sendNotification($row, $msg, false);
        }

        if ($flush)
        {
            $this->flush();
        }
    }
1019792
public function SendMail($oArticle = null, $sEmail = '')
    {
        // ------------------------------------------------------------------------
        static $aPortals = array();
        if (null === $oArticle) {
            $oArticle = $this->GetFieldShopArticle();
        }
        if ('' === $sEmail) {
            $sEmail = $this->fieldPreorderUserEmail;
        }
        if (!is_null($oArticle) && !empty($sEmail)) {
            $oMail = TdbDataMailProfile::GetProfile('preorder-available');
            $sArticleDetailLink = $oArticle->GetDetailLink(true);

            if (!array_key_exists($this->fieldCmsPortalId, $aPortals)) {
                $oCMSPortal = TdbCmsPortal::GetNewInstance();
                if ($oCMSPortal->Load($this->fieldCmsPortalId)) {
                    $aPortals[$this->fieldCmsPortalId] = $oCMSPortal;
                }
            }

            $sArticleBasketLink = '';
            if (array_key_exists($this->fieldCmsPortalId, $aPortals)) {
                $sArticleBasketLink = 'http://'.$aPortals[$this->fieldCmsPortalId]->GetPrimaryDomain().'/'.TdbShopArticle::URL_EXTERNAL_TO_BASKET_REQUEST.'/id/'.urlencode($oArticle->id);
            }

            $oMail->AddData('sUserEmail', $sEmail);
            $oMail->AddData('sArticleName', $oArticle->GetName());
            $oMail->AddData('sArticleDetailLink', $sArticleDetailLink);
            $oMail->AddData('sArticleBasketLink', $sArticleBasketLink);

            $oMail->ChangeToAddress($sEmail);
            $oMail->SendUsingObjectView('emails', 'Customer');

            $this->AllowEditByAll(true);
            $this->Delete();
            $this->AllowEditByAll(false);

            return true;
        } else {
            return false;
        }
    }
1339746
private function createOrderInvoice($order, $transactionId, $amount)
    {
        if ($order->getTotalInvoiced() + $amount == $order->getGrandTotal()) {
            $invoice = $this->invoiceService->prepareInvoice($order);
        } else {
            $invoice = $this->invoiceService->prepareInvoiceWithoutItems($order, $amount);
        }

        $invoice->setRequestedCaptureCase(Invoice::CAPTURE_OFFLINE);
        $invoice->setTransactionId($transactionId);
        $invoice->setBaseGrandTotal($amount);
        $invoice->setGrandTotal($amount);
        $invoice->register();
        $invoice->save();

        $order->addRelatedObject($invoice);

        if (!$invoice->getEmailSent()) {
            $this->invoiceSender->send($invoice);
        }

        //Add notification comment to order
        $order->addStatusHistoryComment(
            __('Invoice #%1 is created. Notification email is sent to customer.', $invoice->getId())
        )->setIsCustomerNotified(true)->save();

        return $invoice;
    }
1284221
private function addInvoice($trans, $invoice_no, $ref_no, $options)
    {
        $trans->addChild('InvoiceNo', $invoice_no);
        $trans->addChild('RefNo', $ref_no ?: $invoice_no);
        if ($options['merchant']) {
            $trans->addChild('OperatorID', $options['merchant']);
        }
        if ($options['description']) {
            $trans->addChild('Memo', $options['description']);
        }
    }
1125234
public function sendAdvertPurchaseNotification(Invoice $invoice)
    {
        $templateName = 'PaymentBundle:Email:advert.notification.admin.html.twig';

        if($invoice->getTransaction()->getActor() instanceof Actor){
            $email = $invoice->getTransaction()->getActor()->getEmail();
        }elseif($invoice->getTransaction()->getOptic() instanceof Optic){
            $email = $invoice->getTransaction()->getOptic()->getEmail();
        }
        $context = array(
            'order_number'    => $invoice->getTransaction()->getTransactionKey(),
            'invoice_date'      => $invoice->getCreated(),
            'user_email'        => $email,
            'order_details_url' => $this->router->generate('payment_checkout_showinvoice', array('number' => $invoice->getInvoiceNumber()), UrlGeneratorInterface::ABSOLUTE_URL),
        );

        $this->sendMessage($templateName, $context, $this->twigGlobal->getParameter('admin_email'), $this->twigGlobal->getParameter('admin_email'));
    }
124154
protected function sendMail(Job $job, $template, $subject, $adminMail = false)
    {
        $mail = $this->mailer->get('htmltemplate');
        $mail->setTemplate($template)
             ->setSubject($subject)
             ->setVariables(
                 array(
                                'job'      => $job,
                                'siteName' => $this->options['siteName'],
                            )
             );

        if ($adminMail) {
            $mail->setTo($this->options['adminEmail']);
        } else {
            if (! ($user = $job->getUser())) {
                return;
            }
            $userInfo  = $user->getInfo();
            $userEmail = $userInfo->getEmail();
            $userName  = $userInfo->getDisplayName(/*emailIfEmpty*/ false);

            $mail->setTo($userEmail, $userName);
        }

        $this->mailer->send($mail);
    }
102450
public function cancel(string $id)
    {
        // Log Debug
        $this->flow->getLogger()->debug("Cancelling Invoice $id");

        return $this->make(
            $this->flow->send(
                'post',
                $this->endpoint . '/cancel',
                [
                    $this->id => $id,
                ]
            )
        );
    }
1078739
protected function mailInvoiceAddResult(Result $result, Source $invoiceSource)
    {
        $pluginSettings = $this->getConfig()->getPluginSettings();
        $addReqResp = $pluginSettings['debug'] === PluginConfig::Send_SendAndMailOnError ? Result::AddReqResp_WithOther : Result::AddReqResp_Always;
        if ($addReqResp === Result::AddReqResp_Always || ($addReqResp === Result::AddReqResp_WithOther && $result->hasMessages())) {
            return $this->getMailer()->sendInvoiceAddMailResult($result, $invoiceSource->getType(), $invoiceSource->getReference());
        }
        return true;
    }
1226481
public function sendEmail( $emailAddress, $templateId, array $personalisation = array(), $reference = '', $emailReplyToId = NULL ){

        return $this->httpPost(
            self::PATH_NOTIFICATION_SEND_EMAIL,
            $this->buildEmailPayload( 'email', $emailAddress, $templateId, $personalisation, $reference, $emailReplyToId )
        );

    }
207843
public static function sendMail($from,$to,$title,$content,$is_html=1){
		$m = self::getMailOb($from,$to,$title,$content,$is_html);
		if($m){
			$m->send();
			return true;
		}
		
		return false;
	}
1159924
protected function sendEmail(MailerInterface $mailer, $address)
    {
        $message = $mailer->compose();
        $message->setTextBody(file_get_contents($this->_output))
            ->setSubject($this->getEmailSubject())
            ->setTo($address);

        $message->send();
    }
138716
public function send()
    {
        $aReminder = $this->json();
        $aReminder = json_decode($aReminder, true);

        $aReminder['sales_invoice_ids'] = array_map(function ($salesInvoice) {
            if (is_object($salesInvoice)) {
                return $salesInvoice->id;
            } else {
                return $salesInvoice;
            }
        }, $this->sales_invoices);
        unset($aReminder['sales_invoices']);

        $this->connection->post($this->endpoint . '/send_reminders', json_encode([
            'sales_invoice_reminders' => [$aReminder],
        ]));
    }