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

Symfony联系表单无法发送邮件,请求故障排查

联系表单提交后未收到邮件的排查方向(Symfony环境)

我使用Symfony搭建了网站并正在部署,配置了联系表单,提交表单后本应收到邮件,但目前未收到任何消息。以下是我的相关配置与代码:

.env配置

MAILER_DSN=smtp://contact@domain.com:password@smtp.mail.host.com:465?encryption=ssl&auth_mode=login

注:原配置中的&需替换为实际的&,否则DSN解析会出错

ContactController.php代码

<?php

namespace App\Controller\Front;

use App\Form\Front\ContactType;
use Symfony\Component\Mime\Email;
use App\Repository\UserRepository;
use App\Form\Front\ContactFromUserType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class ContactController extends AbstractController
{
    #[Route('/contact', name: 'contact')]
    public function index(
        Request $request, 
        UserRepository $userRepository,
        MailerInterface $mailer): Response
    {
        if ($this->getUser()) {
            $connected = $this->getUser();
            $useremail = $connected->getUserIdentifier();
            $user = $userRepository->findOneBy(['email' => $useremail]);

            $form = $this->createForm(ContactFromUserType::class);
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $contactFormData = $form->getData();
                $message = (new Email())
                    ->from($user->getEmail())
                    ->to('contact@email.com')
                    ->subject('Vous avez reçu un email d\'un utilisateur de Go Zpeak : ' . $user->getFirstname() . ' ' . $user->getLastname())
                    ->text(
                        $contactFormData['message'],
                        'text/plain'
                    );
                $mailer->send($message);

                $this->addFlash('success', 'Merci. Ton message a bien été envoyé !');

                return $this->redirectToRoute('contact');
            }

            return $this->render('front/home/contact.html.twig', [
                'form' => $form->createView()
            ]);

        } else {

            $form = $this->createForm(ContactType::class);
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $contactFormData = $form->getData();

                $message = (new Email())
                    ->from($contactFormData['email'])
                    ->to('contact@email.com')
                    ->subject('Vous avez reçu un email d\'un visiteur de Go Zpeak !')
                    ->text(
                        'Nom du visiteur : '.$contactFormData['name'].\PHP_EOL.
                        $contactFormData['message'],
                        'text/plain'
                    );
                try {
                    $mailer->send($message);
                } catch (TransportExceptionInterface $e) {
                    $this->addFlash('error', $e);
                    return $this->redirectToRoute('contact');
                }

                $this->addFlash('success', 'Merci. Ton message a bien été envoyé !');

            }

            return $this->render('front/home/contact.html.twig', [
                'form' => $form->createView()
            ]);
        }
    }
}

可能的问题点

  • 已登录用户分支缺少异常捕获:已登录用户的邮件发送代码没有捕获TransportExceptionInterface异常,即使发送失败也会显示成功提示,导致无法得知实际错误。需要给该分支添加try-catch块,比如:

    try {
        $mailer->send($message);
    } catch (TransportExceptionInterface $e) {
        $this->addFlash('error', '邮件发送失败:' . $e->getMessage());
        return $this->redirectToRoute('contact');
    }
    
  • SMTP配置错误:

    • 检查MAILER_DSN中的密码是否包含特殊字符(如@、&),这类字符需要URL编码后才能正确解析;
    • 确认SMTP服务商的主机、端口、加密方式是否匹配:465端口对应ssl是常规配置,但部分服务商要求使用587端口+tls加密;
    • 验证邮箱账号是否开启了SMTP服务,密码是否正确(比如部分邮箱需要使用应用专用密码而非登录密码);
    • 部署服务器的防火墙/安全组是否允许出站访问465端口。
  • 邮件被拦截:检查收件邮箱的垃圾邮件文件夹,尤其是未登录用户提交的邮件,发件人是用户输入的邮箱,容易被反垃圾系统判定为垃圾邮件。

  • 代码逻辑隐患:

    • 已登录用户分支中,$user = $userRepository->findOneBy(['email' => $useremail]);完全可以替换为$user = $this->getUser();,避免重复查询导致的潜在错误(比如查询不到用户时$user为null,调用getEmail()会触发致命错误);
    • 确认收件邮箱contact@email.com是正确的实际收件地址,而非占位符。
  • 缓存未更新:修改.env配置后,生产环境需要清理缓存,执行命令:

    php bin/console cache:clear --env=prod
    
  • 查看日志定位错误:检查Symfony生产环境日志(var/log/prod.log),日志中会记录邮件发送的详细错误信息,比如SMTP连接失败、认证失败等,这是最直接的排查方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:53:19