Skip to content

How to send e-mail from YII2 Application

Last updated on December 21, 2022

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 provides a flexible interface for sending emails, however, to send emails we have to use external Email libraries/extensions.

Yii2 by default using yii2-swiftmailer as the official extension.

Open your config/wep.php file and make the following adjustments to send emails using the email function.

Find the following:

'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 the advanced YII2 application, the file will be in common/main-local.php by default.

Change the code to this:

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 the above email configuration steps. You can use the below code to send emails.

Yii::$app->mailer->compose()
    ->setFrom('[email protected]')
    ->setTo('[email protected]')
    ->setSubject('Message subject')
    ->setTextBody('Plain text content')
    ->setHtmlBody('HTML content')
    ->send();

See the following link for info on sending emails. http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html

0 0 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments