Mail is sent through the mailer application component.
Historically the official extension was yii2-swiftmailer. SwiftMailer is no longer maintained, so new projects should use open_in_new yii2-symfonymailer
instead. The configuration shape is the same; only the class names differ.
Configuration
return [
// ...
'components' => [
'mailer' => [
'class' => 'yii\symfonymailer\Mailer',
],
],
];
With SwiftMailer (legacy projects):
return [
// ...
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
],
],
];
Gmail SMTP
return [
// ...
'components' => [
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'your-account@gmail.com',
'password' => 'your-app-password',
'port' => '465',
'encryption' => 'ssl',
],
],
],
];
Gmail rejects a plain account password. Enable two-factor authentication and generate an app password for the mailer. (The old “less secure apps” toggle and the DisplayUnlockCaptcha page no longer exist.)
Note useFileTransport: when it is true (the default in the basic template), messages are written to runtime/mail instead of being sent — convenient during development.
Sending a message
Yii::$app->mailer->compose()
->setTo('recipient@example.com')
->setFrom('robot@example.com')
->setSubject('Subject Text')
->setTextBody('Body Text')
->send();
Andrew Dorokhov