3

I wanna add custom CC email to all transactional emails in Magento 2. But, I can't find any decent event to catch email sending process and add CC to email. Any ideas?

UPDATE

As Keyur Shah suggests, I've created di.xml

<config>
<type name="\Magento\Framework\Mail\Template\TransportBuilder">
  <plugin name="test_custompayment_plugin" type="Test\Custompayment\Plugin\TransportBuilder" sortOrder="1" />
</type>

And /Test/Custompayment/Plugin/TransportBuilder.php

<?php
namespace Test\Custompayment\Plugin;

class TransportBuilder
{
public function beforeGetTransport()
{
    $this->prepareMessage();
    $this->addCc('sevkafaya@gmail.com','');
    $mailTransport = $this->mailTransportFactory->create(['message' => clone $this->message]);
    $this->reset();
    return $mailTransport;
   }
}

But I face with error:

Fatal Error: 'Uncaught Error: Call to undefined method Test\Custompayment\Plugin\TransportBuilder::prepareMessage()

So do I need copy all content from \Magento\Framework\Mail\Template\TransportBuilder and just replace getTransport() with beforeGetTransport?

  • 1
    Did you try my answer? – Keyur Shah Jan 29 '18 at 8:11
  • Still not, but will try today. Thanks. Will appreciate if you demonstrate di.xml for overriding TransportBuilder class – k2rakas Jan 29 '18 at 13:22
  • I already gave a link in my answer, you can try it your end. Still, If you face any problem then just let me know :) – Keyur Shah Jan 29 '18 at 13:55
2

Magento2 use \Magento\Framework\Mail\Template\TransportBuilder to configure and send an email so I would suggest you to write a before plugin for this class and and method is getTransport() method.

On before plugin you can add your custom email address as addCc().

1

use after method

    public function afterGetTransport($subject, $result) 
{
    $result->getMessage()->addCc('sevkafaya@gmail.com','');     
    return $result;
}   
0

@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>
0

This feature is built into Magento core

You have the option to configure cc for many of the different transactional emails

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.