PHP项目Symfony MIME与邮件

wen PHP项目 2

本文目录导读:

PHP项目Symfony MIME与邮件

  1. Symfony MIME组件
  2. Symfony Mailer组件
  3. 常用配置和最佳实践

我来帮您系统地介绍Symfony框架中的MIME组件和邮件处理功能。

Symfony MIME组件

安装

composer require symfony/mime

创建和操作邮件

use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
// 创建基本邮件
$email = (new Email())
    ->from('sender@example.com')
    ->to('recipient@example.com')
    ->cc('cc@example.com')
    ->bcc('bcc@example.com')
    ->replyTo('reply@example.com')
    ->priority(Email::PRIORITY_HIGH)
    ->subject('欢迎信息')
    ->text('这是邮件的正文内容')
    ->html('<h1>欢迎</h1><p>这是HTML格式的邮件内容</p>');

添加附件

// 添加文件附件
$email->attachFromPath('/path/to/file.pdf', 'document.pdf', 'application/pdf');
附件(直接使用字符串)
$email->attach('PDF内容', 'report.pdf', 'application/pdf');
// 添加嵌入图片(内联图片)
$email->embedFromPath('/path/to/image.jpg', 'logo');

使用命名地址

use Symfony\Component\Mime\NamedAddress;
$email->from(new NamedAddress('admin@example.com', 'Admin'));
$email->to(new NamedAddress('john@example.com', 'John Doe'));

Symfony Mailer组件

安装

composer require symfony/mailer

配置邮件发送器

config/packages/mailer.yaml

framework:
    mailer:
        dsn: '%env(MAILER_DSN)%'

环境配置 (.env)

# SMTP配置
MAILER_DSN=smtp://user:pass@smtp.example.com:587
# Gmail
MAILER_DSN=gmail+smtp://user:pass@default
# Mailtrap(测试用)
MAILER_DSN=smtp://user:pass@smtp.mailtrap.io:2525
# Sendmail(本地)
MAILER_DSN=sendmail://default
# 本地调试(不实际发送)
MAILER_DSN=null://null

发送邮件

use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
class MailService
{
    private MailerInterface $mailer;
    public function __construct(MailerInterface $mailer)
    {
        $this->mailer = $mailer;
    }
    public function sendWelcomeEmail(string $recipientEmail): void
    {
        $email = (new Email())
            ->from('noreply@example.com')
            ->to($recipientEmail)
            ->subject('欢迎加入我们的平台')
            ->html('<h1>欢迎!</h1><p>感谢您的注册。</p>');
        try {
            $this->mailer->send($email);
        } catch (\Exception $e) {
            // 处理发送失败
            throw new \RuntimeException('邮件发送失败: ' . $e->getMessage());
        }
    }
}

创建自定义邮件模板

// src/Email/WelcomeEmail.php
namespace App\Email;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mime\Header\Headers;
use Symfony\Component\Mime\Part\AbstractPart;
class WelcomeEmail extends TemplatedEmail
{
    public function __construct(string $recipientEmail, string $username)
    {
        parent::__construct();
        $this->from('noreply@example.com')
             ->to($recipientEmail)
             ->subject('欢迎加入,' . $username)
             ->htmlTemplate('emails/welcome.html.twig')
             ->context([
                 'username' => $username,
             ]);
    }
}

使用Twig模板

templates/emails/welcome.html.twig

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h1>欢迎 {{ username }}!</h1>
    <p>感谢您注册我们的平台。</p>
    <p>
        <a href="{{ url('app_login') }}">点击此处登录</a>
    </p>
</body>
</html>

发送方法

// 在控制器中使用
use App\Email\WelcomeEmail;
use Symfony\Component\Mailer\MailerInterface;
class RegistrationController extends AbstractController
{
    #[Route('/register', name: 'app_register')]
    public function register(MailerInterface $mailer): Response
    {
        // ... 注册逻辑
        $email = new WelcomeEmail($user->getEmail(), $user->getUsername());
        $mailer->send($email);
        return $this->redirectToRoute('app_home');
    }
}

邮件事件和监听器

// 使用事件监听
use Symfony\Component\Mailer\Event\MessageEvent;
class MailLoggerListener
{
    public function onMessage(MessageEvent $event): void
    {
        $message = $event->getMessage();
        // 记录邮件信息
        $this->logger->info('邮件发送: ' . $message->getSubject());
    }
}

测试邮件

// 使用MailerAssertionsTrait进行测试
use Symfony\Bundle\FrameworkBundle\Test\MailerAssertionsTrait;
class MailTest extends WebTestCase
{
    use MailerAssertionsTrait;
    public function testMailIsSent(): void
    {
        $client = static::createClient();
        $client->request('POST', '/register', [
            'email' => 'test@example.com',
        ]);
        $this->assertEmailCount(1);
        $this->assertEmailHeaderSame('test@example.com', 'To');
    }
}

常用配置和最佳实践

延迟发送(异步队列)

# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            async: '%env(MESSENGER_TRANSPORT_DSN)%'
        routing:
            'Symfony\Component\Mailer\Messenger\SendEmailMessage': async

多次尝试

// 配置重试机制
framework:
    mailer:
        dsn: '%env(MAILER_DSN)%'
        envelope:
            sender: 'sender@example.com'
        retry:
            max_retries: 3
            delay: 1000 # 毫秒

邮件调试

# 在开发环境中使用mailpit或mailhog
MAILER_DSN=smtp://localhost:1025
# 或使用日志记录器
MAILER_DSN=null://null

这些是Symfony MIME和Mailer组件的核心功能和使用方法,根据您的具体需求,可以灵活组合这些功能来构建强大的邮件系统。

抱歉,评论功能暂时关闭!