注:本文所有代码示例均来自Symfony官网
Symfony默认使用Swift Mailer发送邮件,如果是通过命令 symfony
new your_project_name 创建的基础项目框架,在 config.yml 中已经有关于 swiftmailer的配置,例如:
# app/config/config.yml
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
备注:百分号中间的参数可在 parameters 中定义。
使用Symfony发送邮件,可概括为:
- 配置
- 创建Swift_Message实例,设置邮件(标题、内容、附件等等)
- 调用swiftmailer的service发送
完成了第一步之后,第二、三步的使用很简单,示例代码:
public function indexAction($name)
{
$message = \Swift_Message::newInstance()
->setSubject('Hello Email')
->setFrom('send@example.com')
->setTo('recipient@example.com')
->setBody( //setBody方法的参数是一个临时渲染的邮件内容模板
$this->renderView(
// app/Resources/views/Emails/registration.html.twig
'Emails/registration.html.twig',
array('name' => $name)
),
'text/html'
)
/*
* If you also want to include a plaintext version of the message
->addPart(
$this->renderView(
'Emails/registration.txt.twig',
array('name' => $name)
),
'text/plain'
)
*/
;
$this->get('mailer')->send($message); // 调用mailer服务发送邮件
return $this->render(...);
}
(完)
参考链接:http://symfony.com/doc/current/email.html
本文介绍了如何在Symfony项目中利用Swift Mailer发送邮件。 Symfony默认配置已在config.yml中,发送邮件主要步骤包括配置、创建Swift_Message实例并设置邮件详情,然后调用swiftmailer服务进行发送。
1173

被折叠的 条评论
为什么被折叠?



