Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

php - How to use the swiftMailer in Yii2

I can't finally understand how to use the swiftMailer extension in Yii2. Judging by that on this subject I didn't find questions, the task is trivial, but up to the end I couldn't understand.

There are examples which don't describe in more detail all cycle of sending the letter or I don't understand something :(

Setup

    return [
    //....
   'components' => [
    ......
    'mail' => [
      'class' => 'yiiswiftmailerMailer',
      'transport' => [
        'class' => 'Swift_SmtpTransport',
        'host' => 'localhost',
        'username' => 'username',
        'password' => 'password',
        'port' => '587',
        'encryption' => 'tls',
      ],
    ],
  ]
];

Send

Yii::$app->mail->compose()
->setTo($toEmail)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();

I want will receive a concrete working example. Thank you.

P.S. I adjusted domain records MX, DKIM, SPF added.

UPD (some answer):

E-mail which is passed in "From" field, it is put down by default in the field of "Return-path", has to be the existing address. Some providers don't allow sending mail from nonexistent email addresses.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Make sure you have initialised your application in production environment to send emails from your application,else it will be written in to the mailoutput folder.Or manually edit the config file like follows.

In the components's section of your common/main-local.php

'mail' => [
        'class' => 'yiiswiftmailerMailer',
        'viewPath' => '@backend/mail',
        'useFileTransport' => false,//set this property to false to send mails to real email addresses
        //comment the following array to send mail using php's mail function
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.gmail.com',
            'username' => '[email protected]',
            'password' => 'password',
            'port' => '587',
            'encryption' => 'tls',
            ],
    ],

In your Controller

    Yii::$app->mail->compose('your_view', ['params' => $params])
    ->setFrom([Yii::$app->params['supportEmail'] => 'Test Mail'])
    ->setTo('[email protected]')
    ->setSubject('This is a test mail ' )
    ->send();

This should work! Hope this will help you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...