How to send emails from the yii2 php framework?
Instructions to configure email SMTP with the yii2 framework (yii2 send email example). The PHP yii2 framework has yiisoft/yii2-symfonymailer library. No need to install this package again.
Step 1: Configure Email SMTP credentials
Modify config/web.php
file. Now, we need to edit the username and password of the SMTP server.
Where can I get SMTP credentials for testing?
Just create MailMug.net free account. Then you can see the SMTP sandbox account credentials from the MailMug.net dashboard > Settings page.
Where can I get SMTP credentials for the production server?
Create an email account for your domain name from cPanel or Plesk or any other server control panel. Then you can see SMTP credentials. Just copy and paste credentials to the config/web.php file.
The config/web.php file
'components' => [
//....
'mailer' => [
'class' => \yii\symfonymailer\Mailer::class,
'transport' => [
'scheme' => 'smtp',
'host' => 'smtp.mailmug.net',
'username' => 'lz5ebosxdq0uruxb',
'password' => 'kbs6m4hifn8di3gi',
'port' => 2525,
],
'viewPath' => '@app/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure transport
// for the mailer to send real emails.
'useFileTransport' => false,
],
//..
];
Step 2: Test it
You can send emails from controllers or models. Check the following code.
namespace app\controllers;
use Yii;
class PostController extends \yii\web\Controller
{
public function actionIndex()
{
$this->send();
return $this->render('index');
}
public function send()
{
Yii::$app->mailer->compose()
->setTo('your@email.com')
->setFrom([Yii::$app->params['senderEmail'] => Yii::$app->params['senderName']])
->setSubject('Test Subject')
->setTextBody('Test Body')
->send();
}
}
How to add an HTML email template from the Yii framework?
The HTML email template is already available in the mail/layouts
folder. Pass email template name to compose
method.
Example:
Yii::$app->mailer->compose('layouts/html', ['content' => 'Some data here'])
->setTo('your@email.com')
->setFrom([Yii::$app->params['senderEmail'] => Yii::$app->params['senderName']])
->setSubject('Test Subject')
->send();
How to send an email with an attachment?
Pass the file name with the path in attach
method.
Example:
Yii::$app->mailer->compose('layouts/html', ['content' => 'Some data here'])
->setTo('your@email.com')
->setFrom([Yii::$app->params['senderEmail'] => Yii::$app->params['senderName']])
->setSubject('Test Subject')
->attach('/path/drawing.svg', ['fileName' => 'drawing.svg'])
->attach('/path/drawing1.svg', ['fileName' => 'drawing1.svg'])
->send();