You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AbstractMailService中添加从路由接收的附件?

使用AbstractMailService处理带附件的联系表单邮件

1. 配置路由接收带附件的表单数据

首先确保路由支持multipart/form-data请求(涉及文件上传),在自定义插件的控制器中处理POST请求,提取表单字段与上传附件:

// 自定义插件控制器类
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

class ContactFormController
{
    public function __construct(private readonly ContactMailService $mailService) {}

    public function submit(Request $request): JsonResponse
    {
        // 提取表单文本字段
        $name = $request->request->get('name');
        $senderEmail = $request->request->get('email');
        $message = $request->request->get('message');

        // 获取上传的附件(需与前端表单文件字段名对应,示例为attachments)
        $uploadedFiles = $request->files->get('attachments', []);

        // 调用邮件服务发送
        $this->mailService->sendContactMessage($name, $senderEmail, $message, $uploadedFiles);

        return new JsonResponse(['status' => '邮件已发送']);
    }
}

2. 实现继承AbstractMailService的邮件服务

创建自定义邮件服务类,继承AbstractMailService,核心是将上传的UploadedFile转换为邮件可识别的DataPart附件并添加到邮件中:

use Shopware\Core\Framework\Mail\AbstractMailService;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\Mail\MailException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\DataPart;

class ContactMailService extends AbstractMailService
{
    public function sendContactMessage(string $name, string $senderEmail, string $message, array $uploadedFiles = [], Context $context = null): void
    {
        // 初始化邮件对象
        $email = (new Email())
            ->from($senderEmail)
            ->to('support@your-shop.com')
            ->subject("新联系表单: {$name}")
            ->text(<<<TEXT
姓名: {$name}
邮箱: {$senderEmail}

留言内容:
{$message}
TEXT);

        // 遍历处理上传的附件
        foreach ($uploadedFiles as $file) {
            // 跳过无效文件
            if (!$file instanceof UploadedFile || !$file->isValid()) {
                continue;
            }

            // 可选:验证文件类型,仅允许PDF、PNG等指定类型
            $allowedTypes = ['application/pdf', 'image/png', 'image/jpg', 'image/jpeg'];
            if (!in_array($file->getClientMimeType(), $allowedTypes)) {
                continue; // 也可抛出异常提示用户上传非法文件
            }

            // 创建邮件附件并添加到邮件
            $attachment = DataPart::fromPath(
                $file->getPathname(),
                $file->getClientOriginalName(),
                $file->getClientMimeType()
            );
            $email->attach($attachment);
        }

        // 调用父类方法发送邮件
        try {
            $this->send($email, $context ?? Context::createDefaultContext());
        } catch (MailException $e) {
            // 添加日志记录或异常处理逻辑
            throw new \RuntimeException('邮件发送失败: ' . $e->getMessage(), $e->getCode(), $e);
        }
    }
}

3. 关键注意事项

  • 路由配置:确保路由的请求解析支持multipart/form-data,Symfony/Shopware环境默认支持,但需前端请求正确设置Content-Type。
  • 文件验证:必须验证上传文件的类型和大小,防止恶意文件上传或过大文件增加服务器负载。
  • 临时文件处理:UploadedFile的临时文件会在请求结束后自动清理,需确保邮件发送完成前不提前销毁这些文件。
  • 服务注册:若为Shopware插件,需在services.xml中正确注册邮件服务,确保依赖注入正常工作。

内容的提问来源于stack exchange,提问作者Stepan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 16:05:30