How to use the swiftMailer in Yii2 How to use the swiftMailer in Yii2 php php

How to use the swiftMailer in Yii2


Make sure you have initialised your application in production environment to send emails from your application,else it will be written in to the mailoutput folder.Or manually edit the config file like follows.

In the components's section of your common/main-local.php

'mail' => [        'class' => 'yii\swiftmailer\Mailer',        'viewPath' => '@backend/mail',        'useFileTransport' => false,//set this property to false to send mails to real email addresses        //comment the following array to send mail using php's mail function        'transport' => [            'class' => 'Swift_SmtpTransport',            'host' => 'smtp.gmail.com',            'username' => 'username@gmail.com',            'password' => 'password',            'port' => '587',            'encryption' => 'tls',            ],    ],

In your Controller

    \Yii::$app->mail->compose('your_view', ['params' => $params])    ->setFrom([\Yii::$app->params['supportEmail'] => 'Test Mail'])    ->setTo('to_email@xx.com')    ->setSubject('This is a test mail ' )    ->send();

This should work! Hope this will help you!


You need not using SMTP transport with swiftmailer, only remove 'useFileTransport' => true in the config file (app/config/web.php in basic template) and the mails will flow.

Take a look in the docs:

http://www.yiiframework.com/doc-2.0/ext-swiftmailer-index.html


Warning: This option no longer available, as Mandrill was bought by Mailchimp

Sometimes could be issues with using SwiftMailer not dependent from you. Like when I used mail.ru e-mail server.I found solution in laravel community and implemend in Yii2.

You can use alternative service like https://mandrillapp.com/ (12k email per month, 250 within hour is free) and setting up like below:

laravel community / setup mail with mandrill

'host' => 'smtp.mandrillapp.com','username' => 'user@domain.name','password' => 'oDLKswXZIkry8634f1jCDg', // new generated API key by mandrill'port' => '587','encryption' => 'tls',

If you are using gmail email you can also can face with security issue. You can swith off security by allowing application use your gmail account.

If you signed in with google use links below:

https://www.google.com/settings/security/lesssecureapps

Hope it will help somebody