Sometime you need a small script to send a simple email. For example to warn a store owner that a import has failed. This code snippet shows you, in my opinion, the best way to send such email. Without bypassing all the Magento plugins that enable or disable emails and ore add important headers.
<?php
namespace Experius\SendSimpleEmailExample\Model;
class Mail
{
protected $messageFactory;
protected $mailTransportFactory;
public function __construct(
\Magento\Framework\Mail\Message $messageFactory,
\Magento\Framework\Mail\TransportInterfaceFactory $transportInterfaceFactory
) {
$this->messageFactory = $messageFactory;
$this->mailTransportFactory = $transportInterfaceFactory;
}
public function sendMessage()
{
$message = $this->messageFactory;
$message->setMessageType('html');
$message->setFrom('custom2@example.com');
$message->addTo('johndoe@example.com');
$message->setBodyHtml('<strong>Hello Email</strong>');
$message->setSubject('Simple Email Example');
$mailTransport = $this->mailTransportFactory->create(['message' => $message]);
$mailTransport->sendMessage();
}
}
?>
You can also checkout the example module on our github
https://github.com/experius/Magento-2-Module-Experius-SendSimpleEmailExample