@keyur-shah 's answer definitely gave me the clue. I share my result here - just in case anyone needs it. As suggested, I have created a plugin that hooks into the \Magento\Framework\Mail\Template\TransportBuilder\getTransport
method via a before
hook.
I also made the cc address configurable via admin. For this purpose, I needed dependency injection and an additional constructor. Is dependency injection possible for plugins? helped me with this.
This is my core plugin file:
CcPlugin.php:
<?php
/**
* MyCompany Email.
*/
namespace MyCompany\Email\Plugin;
use Magento\Framework\Mail\Template\TransportBuilder;
/**
* Class CcPlugin.
*/
class CcPlugin extends \Magento\Framework\Mail\Template\TransportBuilder
{
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
/**
* CcPlugin constructor.
*
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Psr\Log\LoggerInterface $logger
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Psr\Log\LoggerInterface $logger
) {
$this->scopeConfig = $scopeConfig;
$this->logger = $logger;
}
/**
* Set cc for transactional emails, if configured via admin.
*/
public function beforeGetTransport(TransportBuilder $subject)
{
try {
$path = 'email/general/cc';
if ($this->scopeConfig) {
$ccEmailAddress = $this->scopeConfig->getValue(
$path,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
if (!empty($ccEmailAddress)) {
$subject->addCc($ccEmailAddress);
}
}
} catch (\Exception $e) {
$this->logger->error('Failure in MyCompany Cc module: ' . $e->getMessage());
}
return [];
}
}
The di.xml
file was required for the plugin:
<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
* MyCompany Email.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Mail\Template\TransportBuilder">
<plugin name="mycompany_email" type="MyCompany\Email\Plugin\CcPlugin"/>
</type>
</config>
Finally, I added a field to the admin configuration via system.xml
. You need to fit this into an existing system.xml
, as it is just an excerpt of a larger system.xml in my case.
<section id="email" translate="label" type="text" sortOrder="80" showInDefault="1">
<class>separator-top</class>
<label>Emails</label>
<tab>mycompany</tab>
<resource>MyCompany_Email::config_section</resource>
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>General Settings</label>
<field id="cc" translate="label comment" type="text" sortOrder="20" showInDefault="1">
<label>CC Email Address</label>
<comment>A cc copy of any transactional email will be sent to this address. Leave empty to switch off.</comment>
</field>
</group>
</section>