How to send email in Yii2 framework

In this post i will show you how to send an email using yii2 framework.Actually in yii2 framework its very easy to configure your email settings in config file.Yii2 provide a easy solution for your email settings and its using yii2-swiftmailer library for by default.

Yii2 Swiftmailer



Step 1: Open your config file located in common/config/main-local.php (i'm using advanced application of yii2).Add the below code under component array.

<?php
return [
    'components' => [
        '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' => false,
            //'enableProfiling' => false,
            //'enableParamLogging' => true,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.gmail.com',
                'username' => '',
                'password' => '',
                'port' => '',
                'encryption' => 'tls',
            ],
        ],
    ],
];

useFileTransport must be changed to false and transport is set to use Swift_MailTransport in your yii2 application.

Step 2: After the configuration settings you can use it.

Yii::$app->mailer->compose()
    ->setFrom('from@yourdomain.com')
    ->setTo('to@yourdomain.com')
    ->setSubject('Message subject')
    ->setTextBody('Plain text content')
    ->setHtmlBody('<b>HTML content</b>')
    ->send();

You can also read the mailer class in yii2.I hope you like the post and please comment if you need any help related to this post.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular