如何阻止Shopware通过Enlight_Components_Mail_Send事件发送邮件?
Hey there! Let's tackle your two Shopware mail-related questions clearly and practically:
Enlight_Components_Mail_Send 事件发送邮件 Shopware triggers the Enlight_Components_Mail_Send event right before an email is actually sent, so you can intercept this to block delivery entirely. Here are two reliable methods:
方法一:中断事件传播
通过调用事件参数的 stopPropagation() 方法,你可以打断事件链——这意味着Shopware内置的发送逻辑(以及后续其他监听器)都不会再执行。如果你想直接拦截所有匹配的邮件,这是个很棒的方案。
示例订阅器类:
namespace YourPluginName\Subscriber; use Enlight_Event_EventArgs; use Enlight_Event_EventHandlerInterface; class MailSendBlocker implements Enlight_Event_EventHandlerInterface { public static function getSubscribedEvents(): array { return [ 'Enlight_Components_Mail_Send' => 'onMailSend' ]; } public function onMailSend(Enlight_Event_EventArgs $args): void { // 可选:添加条件逻辑,只拦截特定邮件 $mail = $args->get('mail'); if (str_contains($mail->getSubject(), '测试订单确认')) { $args->stopPropagation(); } } }
方法二:标记邮件为已发送
你可以通过将邮件对象标记为“已发送”,让Shopware跳过发送步骤。因为Shopware在尝试投递前会检查这个状态。
修改回调函数如下:
public function onMailSend(Enlight_Event_EventArgs $args): void { $mail = $args->get('mail'); // 设置邮件为已发送状态,绕过实际投递 $mail->setSent(true); }
别忘了在插件的 services.xml(或等效配置文件)中注册你的订阅器:
<service id="your_plugin.mail_send_blocker" class="YourPluginName\Subscriber\MailSendBlocker"> <tag name="shopware.event.subscriber"/> </service>
简短回答:当然可以,上面的方法就能实现。
Enlight_Components_Mail_Send 事件是在核心发送函数运行之前触发的。无论是中断事件传播(终止所有下游逻辑)还是标记邮件为已发送(让核心逻辑跳过投递),都能有效阻止Shopware执行该事件关联的实际邮件发送操作。
如果你需要更精细的控制,可以在订阅器中添加条件判断,只拦截符合特定规则的邮件——比如特定主题、收件地址,或者由特定操作触发的邮件(例如订单状态更新)。
内容的提问来源于stack exchange,提问作者Nem Par

