SwiftMailer e-mail library

Many web applications need to send notifications and confirm client actions by e-mail for security reasons. The Yii2 framework provides a wrapper, yiisoft/yii2-swiftmailer, for the established library SwiftMailer.

Getting ready

Create a new application by using composer, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.

Both basic and advanced applications contain this extension out of the box.

How to do it…

Now we will try to send any kind of e-mails from our own application.

Sending plain text e-mails

  1. Set the mailer configuration into the config/console.php file:
    'components' => [
        // ...
        'mailer' => [
            'class' => 'yiiswiftmailerMailer',
            'useFileTransport' => true,
        ],
        // ...
    ],
  2. Create a test console controller, MailController, with the following code:
    <?php
    
        namespace appcommands;
    
        use yiiconsoleController;
        use Yii;
    
        class MailController extends Controller
        {
            public function actionSend()
            {
                Yii::$app->mailer->compose()
                ->setTo('[email protected]')
                ->setFrom(['[email protected]' => Yii::$app->name])
                ->setSubject('My Test Message')
                ->setTextBody('My Text Body')
                ->send();
        }
    }
  3. Run the following console command:
    php yii mail/send
    
  4. Examine your runtime/mail directory. It should contain files with your mails.

    Note

    Note: Mail files contain messages in the special e-mail source format, compatible with any mailing software. You can open this field as a plain text too.

  5. Set the useFileTransport parameter as false or remove this string from the configuration:
    'mailer' => [
        'class' => 'yiiswiftmailerMailer',
    ],

    Then put your real e-mail ID into the setTo() method:

     ->setTo('[email protected]')
  6. Run the console command again:
    php yii mail/send
    
  7. Check your inbox directory.

Note

Note: SwiftMailer uses a standard PHP function, mail(), for sending mails by default. Please check that your server is correctly configured for sending mails via the mail() function.

Many mail systems reject mails without DKIM and SPF signatures (sent by the mail() function as example) or put them into a Spam folder.

Sending HTML content

  1. Check that your application contains the mail/layouts/html.php file and add the mail/layouts/text.php file with the following content:
    <?php
    /* @var $this yiiwebView */
    /* @var $message yiimailMessageInterface */
    /* @var $content string */
    ?>
    <?php $this->beginPage() ?>
    <?php $this->beginBody() ?>
    <?= $content ?>
    <?php $this->endBody() ?>
    <?php $this->endPage() ?>
  2. Create your own view in the mail/message-html.php file:
    <?php
    use yiihelpersHtml;
    
    /* @var $this yiiwebView */
    /* @var $name string */
    ?>
    
    <p>Hello, <?= Html::encode($name) ?>!</p>

    Create a mail/message-text.php file with the same content, but without HTML tags:

    <?php
        use yiihelpersHtml;
    
    /* @var $this yiiwebView */
    /* @var $name string */
    ?>
    
         Hello, <?= Html::encode($name) ?>!
  3. Create a console controller, MailController, with the following code:
    <?php
    
        namespace appcommands;
    
        use yiiconsoleController;
        use Yii;
    
        class MailController extends Controller
        {
            public function actionSendHtml()
            {
                $name = 'John';
    
                Yii::$app->mailer->compose('message-html',['name' => $name])
                ->setTo('[email protected]')
                ->setFrom(['[email protected]' => Yii::$app->name])
                ->setSubject('My Test Message')
                ->send();
            }
    
            public function actionSendCombine()
            {
                $name = 'John';
    
                Yii::$app->mailer->compose(['html' => 
                'message-html', 'text' => 'message-text'], [
                'name' => $name,
                ])
                ->setTo('[email protected]')
                ->setFrom(['[email protected]' 
                    => Yii::$app->name])
                ->setSubject('My Test Message')
                ->send();
            }
    }
  4. Run the following console commands:
    php yii mail/send-html
    php yii mail/se
    nd-combine
    

Working with SMTP transport

  1. Set the transport parameter for the mailer component like this:
    'mailer' => [
        'class' => 'yiiswiftmailerMailer',
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => '[email protected]',
            'password' => 'password',
            'port' => '587',
            'encryption' => 'tls',
        ],
    ],
  2. Write and run the following code:
    Yii::$app->mailer->compose()
        ->setTo('[email protected]')
        ->setFrom('[email protected]')
        ->setSubject('My Test Message')
        ->setTextBody('My Text Body')
        ->send();
  3. Check your Gmail inbox.

Note

Note: Gmail automatically rewrites the From field to your default profile e-mail ID, but other e-mail systems do not do the same. Always use an identical e-mail ID in the transport configuration and in the setFrom() method for passing antispam policies for other e-mail systems.

Attaching file and embedding images

Add the corresponding method to attach any file to your mail:

class MailController extends Controller
{
    public function actionSendAttach()
    {
        Yii::$app->mailer->compose()
            ->setTo('[email protected]')
            ->setFrom(['[email protected]' => Yii::$app->name])
            ->setSubject('My Test Message')
            ->setTextBody('My Text Body')
            ->attach(Yii::getAlias('@app/README.md'))
            ->send();
    }
}

Or use the embed() method in your e-mail view file to paste an image in your e-mail content:

<img src="<?= $message->embed($imageFile); ?>">

It automatically attaches an image file and inserts its unique identifier.

How it works…

The wrapper implements the base yiimailMailerInterface. Its compose() method returns a message object (an implementation of yiimailMessageInterface).

You can manually set plain text and HTML contents with the help of methods setTextBody() and setHtmlBody(), or you can pass your view and view parameters into the compose() method. In this case, the mailer calls the yiiwebView::render() method for rendering corresponding content.

The useFileTransport parameter stores mails in files instead of real sending. It is helpful for local development and application testing.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.109