arrow_back
Back

Yii2 sending emails: mailer component and SMTP transport

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

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();
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 console actions: bootstrapping an app and running actions

arrow_forward