Last updated on 2023年2月13日
How to use symfony/mailer and twig without the Symfony Framework
2021 8月19日,Fabien Potenciar正式宣布Swiftmailer的维护结束。Swiftmailer 已被symfony/mailer 包所取代。
背景
想在 tp6.1.1 中使用 mailer 来发送邮件,邮件内容最好是能使用 twig 引擎直接渲染好的模板。(其他框架也可以参考)
实施
根据官方文档安装:Sending Emails with Mailer (Symfony Docs)
安装依赖
composer require symfony/mailer
composer require symfony/twig-bridge
composer require "twig/twig:^3.0"
代码示例
1.控制器
use Symfony\Bridge\Twig\Mime\BodyRenderer;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
public function sendMail($param)
{
// MAILER_DSN=smtp://user:pass@smtp.example.com:port
$transport = Transport::fromDsn('smtp://user:pass@smtp.example.com:port');
$mailer = new Mailer($transport);
// $email = (new Email())
$email = (new TemplatedEmail())
->from(new Address('from@example.com', '邮件发送人'))
->to('to@example.com')
//->cc('cc@example.com')
//->bcc('bcc@example.com')
->subject($subject)
// ->text('Sending emails is fun again!')
// ->html('<p>See Twig integration for better HTML integration!</p>')
// // path of the Twig template to render
->htmlTemplate('emails/signup.html.twig')
// pass variables (name => value) to the template
->context([
'expiration_date' => new \DateTime('+7 days'),
'username' => 'foo',
]);
// 手动加载模板渲染环境
$loader = new FilesystemLoader(app_path() . 'path/view/');
$twig = new Environment($loader);
$twigBodyRenderer = new BodyRenderer($twig);
$twigBodyRenderer->render($email);
// dd($email->toString());
try {
$mailer->send($email);
} catch (TransportExceptionInterface $e) {
// some error prevented the email sending; display an
// error message or try to resend the message
dump($e->getMessage());
}
}
2.模板文件
{# templates/emails/signup.html.twig #}
<h1>Welcome {{ email.toName }}!</h1>
<p>
You signed up as {{ username }} the following email:
</p>
<p><code>{{ email.to[0].address }}</code></p>
<p>
<a href="#">Click here to activate your account</a>
(this link is valid until {{ expiration_date|date('F jS') }})
</p>
内嵌图片
由于不在 symfony 框架下使用,可以通过 内嵌 图片设置别名 加 图片 cid 的方式
// 后端
$email->embedFromPath('path/to/images/logo.jpg', 'logo')
// 前端
<img src="cid:logo" width=100 height=40 />
CSS内联样式
composer require twig/cssinliner-extra
可以将 css 样式表自动变为内联样式,兼容更多邮件布局
use Twig\Extra\CssInliner\CssInlinerExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new CssInlinerExtension());
模板文件参考官方文档:Sending Emails with Mailer (Symfony Docs)
参考:
https://github.com/symfony/symfony/issues/35990#issuecomment-644532371
How to use symfony/mailer without the Symfony Framework | doeken.org