การส่ง Email ด้วย Yii Framework 2 ผ่าน SMTP ของ Google

wave
มานพ กองอุ่น 26 เม.ย. 2016 03:02:56 14,041

ในบทเรียนรู้นี้มาเรียนรู้การสร้างระบบการส่ง Email แบบใช้ SMTP ของ Google โดยจะต้องมี Account ของ Gmail หรือ สมัครใช้งาน Google Bussiness

SMTP คืออะไร อ่านเพิ่มเติมได้ที่ 

https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol

ใช้ SwifMailer ในการส่งสำหรับ Yii Framework 2 มี Package ที่

http://www.yiiframework.com/doc-2.0/ext-swiftmailer-index.html

ซึ่ง Package นี้จะมาพร้อมตอนติดตั้ง Yii เรียบร้อยแล้ว ไฟล์จะอยู่ที่

yii2-project/vendor/yiisoft/yii2-swiftmailer

 

ตั้งค่า mailer component

ทำการกำหนดค่า mailer component ในไฟล์ common/config/main-local.php โดยแก้ไขส่วนของ mailer ให้ใช้ SMTP ดังนี้

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=yii2-programmer',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
        'mailer' => [ //กำหนดการส่ง Email ผ่าน SMTP ของ Google
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.google.com',
                'username' => 'contact@programmerthailand.com', //user ทีจะใช้ smtp
                'password' => 'your_password',//รหัสผ่านของ user
                'port' => '587',
                'encryption' => 'ssl',
            ],
        ],
    ],
];

Port 587 สำหรับ ssl
Port  465 สำหรับ tls

สามารถดูรายละเอียดการกำหนดสำหรับ Google App ได้ที่

https://support.google.com/a/answer/2956491?hl=th

 

การส่ง Email ส่งได้ 2 แบบ

  1. แบบไม่ใช้ template
  2. แบบใช้ template ซึ่ง template email จะถูกเก็บอยู่ที่ common/mail

ตัวอย่างการส่ง Email เมื่อสมัครสมาชิกเสร็จแล้ว

กำหนดค่า params supportEmail ที่ common/config/params.php

<?php
return [
    'adminEmail' => 'contact@programmerthailand.com',
    'supportEmail' => 'contact@programmerthailand.com', //เพิ่ม supportEmail เอาไว้ใช้อ้างอิงตอนส่ง
    'user.passwordResetTokenExpire' => 3600,
];

สร้าง template email ใน common/mail คือ signupConfirm-text.php และ signupConfirm-html.php

signupConfirm-text.php

<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $user common\models\User */

$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/signup-confirm', 'authkey' => $user->auth_key]);
?>
สวัสดี <?= $user->username ?>,

กรุณาคลิกลิ้งนี้เพื่อยืนยันการสมัครสมาชิกของคุณ :

<?= Html::encode($resetLink) ?>

signupConfirm-html.php

<?php
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $user common\models\User */

$resetLink = Yii::$app->urlManager->createAbsoluteUrl(['site/signup-confirm', 'authkey' => $user->auth_key]);
?>
<div class="password-reset">
    <p>สวัสดี <?= Html::encode($user->username) ?>,</p>

    <p>กรุณาคลิกลิ้งนี้เพื่อยืนยันการสมัครสมาชิกของคุณ :</p>

    <p><?= Html::a(Html::encode($resetLink), $resetLink) ?></p>
</div>

 

เพิ่มการส่ง Email ใน frontend/controllers/SiteController.php ใน actionSignup()

public function actionSignup()
    {
        $model = new SignupForm();
        $profile = new Profile();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {

                $profile->user_id = $user->id;
                $profile->save();

                //ส่งอีเมลล์ยืนยันการสมัครสมาชิก
                //$user->auth_key;
                Yii::$app->mailer->compose(['html' => 'signupConfirm-html', 'text' => 'signupConfirm-text'], ['user' => $user]) //สามารพเลือกเฉพาะ html หรือ text ในการส่ง
                    ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ''])
                    ->setTo($user->email)
                    ->setSubject('ยืนยันผู้ใช้งาน ' . \Yii::$app->name)
                    ->send();

                //if (Yii::$app->getUser()->login($user)) {
                    Yii::$app->session->setFlash('success', 'สมัครสมาชิกเรียบร้อย กรุณาตรวจสอบอีเมลล์เพื่อยืนยันการใช้งานอีกครั้ง');
                    return $this->goHome();
                //}
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

เพียงเท่านี้ก็สามารถส่ง Email ผ่าน SMTP ของ Google ได้

การส่ง Email แบบไม่ใช้ template

ตัวอย่างการส่ง Email แบบไม่ใช้ template ในการตั้งกระทู้ของ Programmer Thailand

$link = Yii::$app->urlManager->createAbsoluteUrl(['/forum/q/view', 'id' => $model->id]);
                Yii::$app->mailer->compose()
                    ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ''])
                    ->setTo(Yii::$app->user->identity->email)
                    ->setSubject('คำถามของคุณที่ ' . \Yii::$app->name)
                    ->setTextBody('หัวข้อ '.$model->subject.' ติดตามคำถามของคุณได้ที่ : '.$link) //เลือกอยางใดอย่างหนึ่ง
                    ->setHtmlBody('หัวข้อ '.$model->subject.' ติดตามคำถามของคุณได้ที่ : '.$link) //เลือกอยางใดอย่างหนึ่ง
                    ->send();

 


ความคิดเห็น

หากบทเรียนรู้มีความผิดพลาดประการใด หรือมีข้อเสนอแนะกรุณาแจ้ง contact@programmerthailand.com

เขียนบทเรียนรู้ของคุณ

รายละเอียด
  • ดู 14,041
  • รักเลย 0
  • หมวดหมู่ Yii Framework 2 (Yii2)
  • เขียนเมื่อ
  • แก้ไขเมื่อ
  • Tags yii send email
ข้อมูลผู้เขียน
มานพ กองอุ่น

มานพ กองอุ่น

เป็นสมาชิกเมื่อ: 18 ธ.ค. 2009

เนื้อหาที่เกี่ยวข้อง