jacquesndl/mailer-bundle

Jacquesndl/MailerBundle

安装: 57

依赖: 0

建议者: 0

安全性: 0

星标: 0

关注者: 1

分支: 0

公开问题: 0

类型:symfony-bundle

1.0.2 2020-06-19 17:19 UTC

This package is auto-updated.

Last update: 2024-09-20 02:17:07 UTC


README

MailerBundle 为 Symfony 邮件组件 添加了一个新的 TemplatedEmail 类。

安装

composer require jacquesndl/mailer-bundle

设置

该组件提供官方配方,帮助您配置组件。

# config/packages/jacquesndl_mailer.yaml

jacquesndl_mailer:
    sender:
        name: '%env(JACQUESNDL_MAILER_SENDER_NAME)%'
        address: '%env(JACQUESNDL_MAILER_SENDER_ADDRESS)%'
# .env

JACQUESNDL_MAILER_SENDER_NAME="Example"
JACQUESNDL_MAILER_SENDER_ADDRESS="example@domain.tld"

环境变量 JACQUESNDL_MAILER_SENDER_NAMEJACQUESNDL_MAILER_SENDER_ADDRESS 定义了发件人的默认值。您可以使用 TemplatedEmail 类的 to() 方法来覆盖它。下面是一个示例。

使用方法

基本

// src/Controller/WelcomeController.php

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Jacquesndl\MailerBundle\Message\TemplatedEmail;

class WelcomeController extends AbstractController
{
    public function index(MailerInterface $mailer): Response
    {
        // ...

        $email = (new TemplatedEmail())
            ->from('didier.deschamps@france.fr') // overwrite the default sender value
            ->to('zinedine.zidane@france.fr')
            ->replyTo('fabien.barthez@france.fr')
            ->template('emails/welcome.email.twig')
            ->attachFromPath('/path/to/documents/coupe-du-monde-1998.pdf')
            ->context([
                'firstName' => 'Zinédine',
            ])
        ;
        
        $mailer->send($email);
        
        // ...
    }
}
{# templates/emails/welcome.email.twig #}

{% block subject %}
   Welcome
{% endblock %}

{% block html %}
   <html>
   <head></head>
   <body>
   <h1>Welcome {{ firstName }}</h1>
   </body>
   </html>
{% endblock %}

{% block text %}
   Your text content
{% endblock %}

如果缺少或空白的 text 块,邮件发送器将自动生成它,通过将 HTML 内容转换为文本。如果您在应用程序中安装了 league/html-to-markdown,则使用它将 HTML 转换为 Markdown(这样文本邮件就有了一些视觉吸引力)。否则,它将应用 strip_tags PHP 函数到原始 HTML 内容。

高级

该组件提供了一个 maker 命令来创建一个扩展 TemplatedEmailEmail 类。

php bin/console make:email WelcomeEmail
// src/Email/WelcomeEmail.php

namespace App\Email;

use Jacquesndl\MailerBundle\Message\TemplatedEmail;

class WelcomeEmail extends TemplatedEmail
{
   protected $template = 'emails/welcome.email.twig';
}
// src/Controller/WelcomeController.php

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use App\Email\WelcomeEmail;

class WelcomeController extends AbstractController
{
    public function index(MailerInterface $mailer): Response
    {
        // ...

        $email = (new WelcomeEmail())
            ->to('zinedine.zidane@france.fr');
        
        $mailer->send($email);
        
        // ...
    }
}