MageWork

Back to home

Send emails

Emails are built from a template, exactly like a page or a block. A mail object
(Core_Mail, type mail) renders an HTML template that you then send.

Mail template

Declare the mail in the block/object configuration and point it to a template:

packages/Acme/etc/config.php

<?php

$config = [
    Core_Mail::TYPE => [
        'contact' => [
            'template' => 'mail/contact',
        ],
    ],
];

Create the template file:

packages/Acme/template/mail/contact.phtml

<?php /** @var Core_Mail $this */ ?>
<h1>New contact message</h1>

<p>From: <?= App::escapeHtml($this->getName()) ?> (<?= App::escapeHtml($this->getEmail()) ?>)</p>
<p><?= nl2br(App::escapeHtml($this->getMessage())) ?></p>

You may also create a class packages/Acme/Mail/Contact.php (`Acme_Mail_Contact extends
Core_Mail`) if the mail needs its own logic.

Render and send

<?php

/** @var Core_Mail $mail */
$mail = App::getSingleton('contact', Core_Mail::TYPE);
$mail->addData([
    'name'    => 'John Doe',
    'email'   => 'john@example.com',
    'message' => "Hello,\nI have a question.",
]);

$html = $mail->render();

// Send it with your preferred transport, or with the native mail() function
mail('contact@example.com', 'New contact message', $html, "MIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n");

With a form

Core_Model_Form sends the email for you when contact settings are enabled (see
Configuration and Forms). Pass the rendered
mail template as the message body:

<?php

/** @var Core_Mail $message */
$message = App::getSingleton('contact', Core_Mail::TYPE);
$message->addData($form->getData());

$form->setMailSubject('New contact message!');
$form->setMailMessage($message->render());
$form->setMailSendTo('contact@example.com');
$form->sendMail();

If setMailMessage() is not called, the form builds a default message from the posted
fields and their labels.