Daniel
Daniel

Reputation: 139

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('[email protected]')
    ->setTo('[email protected]')
    ->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...

Upvotes: 4

Views: 7716

Answers (1)

zilongqiu
zilongqiu

Reputation: 846

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: [email protected]
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: [email protected]
mailer_password: *******

And use it like this

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

Upvotes: 4

Related Questions