Do we need to send a custom email programmatically? In this post, we will send a custom email programmatically.
As we have created a custom email template. We will send an email with this post. Emails are essential for any e-commerce website. We need email for several events, including placing orders.
Magento 2 and Adobe Commerce provide a default email mechanism for all core events. However, we often develop custom functions and must send emails using those functions.
So Let’s send a custom email programmatically.
Magento 2: Send Custom Email Programmatically
<?php
namespace SbDevBlog\Emailer\Services;
use Magento\Framework\App\Area;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\MailException;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Store\Model\Store;
use Magento\Framework\Filesystem\Io\File;
use Magento\Framework\Filesystem\Driver\File as Driver;
use Psr\Log\LoggerInterface;
class EmailService
{
/**
* @var StateInterface
*/
private StateInterface $state;
/**
* @var TransportBuilder
*/
private TransportBuilder $transportBuilder;
/**
* @var LoggerInterface
*/
private LoggerInterface $logger;
/**
* @var File
*/
private File $file;
/**
* @var Driver
*/
private Driver $driver;
/**
* Constructor
*
* @param StateInterface $state
* @param TransportBuilder $transportBuilder
* @param File $file
* @param Driver $driver
* @param LoggerInterface $logger
*/
public function __construct(
StateInterface $state,
TransportBuilder $transportBuilder,
File $file,
Driver $driver,
LoggerInterface $logger
) {
$this->state = $state;
$this->transportBuilder = $transportBuilder;
$this->file = $file;
$this->driver = $driver;
$this->logger = $logger;
}
/**
* Send Email
*
* @param mixed $templateId
* @param string|null $recipient
* @param array $sender
* @param array $emailVariables
* @param array $ccEmail
* @param array $bccEmail
* @param array $attachments
* @return bool
*/
public function sendEmail(
$templateId,
string $recipient,
array $sender = [],
array $emailVariables = [],
array $ccEmail = [],
array $bccEmail = [],
array $attachments = []
): bool {
$this->state->suspend();
try {
$this->transportBuilder
->setTemplateIdentifier($templateId)
->setTemplateOptions(
[
'area' => Area::AREA_FRONTEND,
'store' => Store::DEFAULT_STORE_ID,
]
)
->setTemplateVars($emailVariables)
->setFromByScope($sender)
->addTo($recipient);
if (!empty($ccEmail)) {
$this->transportBuilder->addCc($ccEmail);
}
if (!empty($bccEmail)) {
$this->transportBuilder->addBcc($bccEmail);
}
$transport = $this->transportBuilder->getTransport();
$transport->sendMessage();
$this->state->resume();
} catch (MailException|LocalizedException|\Exception $e) {
$this->logger->info($e->getMessage());
}
$this->state->resume();
}
}
Description:
The TransportBuilder class mentioned in the code is responsible for emailing the respective template IDs and variables.
We must turn off the inline translation before sending transactional emails to ensure it doesn’t conflict with strings rendered inside the email.
Next, We must set the template ID we use to send emails. Next, We must select template options like area (frontend or adminhtml) and store id. The transport builder will pick up the template for the specified store from the respective area.
We must set email variables to send transaction data via email. Set sender information by passing an argument in the function setFromByScope. Also, recipient details are set by passing an argument in the function addTo.
The CC and BCC can be set optionally in the functions addCc and addBcc.
Finally, get the transport from TransportBuilder and send the email using the sendMessage function of the transport class. Also, remember to resume the inline translation, which we stopped before sending the email.
Remember to handle possible errors from the TransportBuilder or the respective class while emailing. Possible types are given below:
\Magento\Framework\Exception\LocalizedException;
\Magento\Framework\Exception\MailException;
\Exception
That’s it. Thanks for reading the post – Magento 2: Send Custom Email Programmatically. Please use the comment box to share your feedback. Also, Please share SbDevBlog with your connections.
Note: Please verify the code of this blog and the relevant git repository before using it in production.
🙂 HAPPY CODING 🙂
One thought on “Magento 2: Send Custom Email Programmatically”