Hi there, This tutorial will show you how to send emails from the yii2 application. Sending emails from the yii2 application is not a tedious task, in fact, we just need to edit/add the config options in your config file.
Yii2 providing a flexible interface for send emails, however, to send emails we have to use external Email libraries/extensions.
Yii2 by default using yii2-swiftmailer
official extension.
Open your config/wep.php
file and make the following adjustments to send emails using email function.
Find the following:
1 2 3 4 5 6 7 8 |
'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@common/mail', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails. 'useFileTransport' => true, ], |
This will be under the components parameters in the config array. In advanced YII2 application, the file will be in common/main-local.php
by default.
Change the code to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
return [ 'components' => [ ... 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@common/mail', 'transport' => [ 'class' => 'Swift_MailTransport', ], 'useFileTransport' => false, ], ], ]; |
useFileTransport
must be changed to false
and transport is set to use Swift_MailTransport
.
See the following link for info on swiftmailer
transport types. http://swiftmailer.org/docs/sending.html#using-the-mail-transport
Basic usage
After completing above email configurations steps. we can use below code to send emails.
1 2 3 4 5 6 7 |
Yii::$app->mailer->compose() ->setSubject('Message subject') ->setTextBody('Plain text content') ->setHtmlBody('<b>HTML content</b>') ->send(); |
See the following link for info on sending emails. http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
The http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html#sthash.8IsboPVL.dpuf seems to be out of date. I’m trying to get an inlined styled email file from a separate html and css file without having to do the inlining of the styles by hand.
Do you have any idea on how to do that? Like convert two files (one html, one css) into an email that is sent with the correct styles?
Very useful post… thank you!
hi arjun,
nice tutorial.
but i got an issue.
how can i know email destination is exist or not ?
i always get return true after i send the email actually that email is not exist.
please help..
thanks in advance