简体   繁体   中英

Symfony 2: how to send an email using Swiftmailer

I am trying to send emails using Swiftmailer with Symfony 2.

This is the simple function in the controller

public function sendEmailAction() {

 $name = 'Test';

 $mailer = $this->get('mailer');
 $message = $mailer->createMessage()
    ->setSubject('Ciao')
    ->setFrom('send@example.com')
    ->setTo('recipient@example.com')
    ->setBody($this->renderView('dashboard/email.html.twig',array('name' => $name)), 'text/html');



    $mailer->send($message);

   return $this->redirectToRoute('dashboard');

In the parameters.yml I have following configuration

parameters:
database_host: 127.0.0.1
database_port: null
database_name: symfony
database_user: root
database_password: null
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
secret: e23a8d7b075fa3c7e56b10186a24cf2790a3169a

And this is the config.yml one

# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host:      "%mailer_host%"
username:  "%mailer_user%"
password:  "%mailer_password%"
spool:     { type: memory }

Unfortunately I cannot send emails...

Please read the documentation about "How to send an Email"

Swift Mailer provides a number of methods for sending emails, including using an SMTP server, using a local install of sendmail, or even using a GMail account.

Example with mail transport

mailer_transport: mail
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null

Example with smtp

mailer_transport: smtp
mailer_encryption: ssl
mailer_auth_mode: login
mailer_host: smtp.gmail.com
mailer_user: your@gmail.com
mailer_password: *******

Example with sendmail : read this

mailer_transport: sendmail
mailer_host: /usr/bin/sendmail # wherever your mail is
#mailer_user: ~
#mailer_password: ~

Example with GMail account

mailer_transport: gmail
mailer_encryption: ssl
mailer_auth_mode: login
mailer_host: smtp.gmail.com
mailer_user: your@gmail.com
mailer_password: *******

And use it like this

    $message = \Swift_Message::newInstance()
        ->setSubject('Hello Email')
        ->setFrom('from@example.com')
        ->setTo('to@example.com')
        ->setBody(
            $this->renderView(
                'HelloBundle:Hello:email.txt.twig',
                array('name' => $name)
            )
        )
    ;
    $this->get('mailer')->send($message);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM