Symfony - 如何发送邮件

本文介绍了如何在Symfony项目中利用Swift Mailer发送邮件。 Symfony默认配置已在config.yml中,发送邮件主要步骤包括配置、创建Swift_Message实例并设置邮件详情,然后调用swiftmailer服务进行发送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注:本文所有代码示例均来自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发送邮件,可概括为:

  1. 配置
  2. 创建Swift_Message实例,设置邮件(标题、内容、附件等等)
  3. 调用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值