thinkphp 整合 swiftmailer 實現郵件發送

thinkphp swiftmailer(phpmailer)

目錄結構

這裏寫圖片描述
圖 1 swiftmailer-phpmailer

將swiftmailer整合到thinkphp中,如上圖 1
我下載的版本是 swiftmailer-5.x, 將目錄裏面的lib文件夾重命名爲swiftmailer,並拷貝到ThinkPHP/Library/Vendor目錄下,如上圖 1

配置

這裏寫圖片描述
圖 2 phpmailer swiftmailer 配置對比

// thinkphp config.php
// 配置swiftmailer郵件發送服務器
'SWIFT_HOST'     => 'smtp.qq.com',
'SWIFT_USERNAME' => '[email protected]',
'SWIFT_PASSWORD' => 'your-password',
從上面的對比可以看出,swiftmailer相比較於phpmailer來說配置簡潔

使用

// 在需要使用的時候直接調用下面(圖)的send_email函數即可,
// 但是需要注意函數的返回值,因爲可以根據返回值來確定是否發送成功
send_email('[email protected]', 'your-email-subject', 'your-email-content');

這裏寫圖片描述
圖 3

同樣的,在自定義的**全局**function.php文件中,
定義一個通過swiftmailer發送郵件的**全局**函數,
方便直接調用,代碼如下:
<?php
// Application/Common/Common/function.php

/**
 * send email by swiftmailer
 *
 * @param  string|array $to      收件人
 * @param  string       $subject 主題
 * @param  string       $content 內容
 * @return int          發送的郵件數目
 */
function send_email($to, $subject, $content)
{
    vendor('swiftmailer.swift_required');

    $transport = Swift_SmtpTransport::newInstance(C('SWIFT_HOST'), 25)
                    ->setUsername(C('SWIFT_USERNAME'))
                    ->setPassword(C('SWIFT_PASSWORD'));

    $mailer  = Swift_Mailer::newInstance($transport);
    $message = Swift_Message::newInstance()
                    ->setSubject($subject)
                    ->setFrom(array(C('SWIFT_USERNAME') => 'safari_shi'))
                    ->setTo($to)
                    ->setBody($content, 'text/html', 'utf-8');

    return $mailer->send($message);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章