SwiftMailer 下載地址:https://github.com/swiftmailer/swiftmailer
版本:swiftmailer-5.x
把壓縮包解壓到 /ThinkPHP/Library/Vendor 中。
配置文件 config.php
<?php return array( //'配置項'=>'配置值' // 郵件配置 'SMTP' => 'smtp.XXX.cn', 'MAIL_PORT' => 25, 'MAIL_USER' => 'XXX@XXX.com', //郵箱用戶名 'MAIL_PWD' => 'XXX', //發送郵箱密碼或者授權碼 'MAIL_FROM' => 'XXX@XXX.com', 'MAIL_FROM_NAME' => 'dee', );
/Application/Home/Common/Swiftmail.class.php
<?php
namespace Home\Common;
class Swiftmail {
// @param $host 郵件服務器地址
// @param $port 端口號
// @param $encryption_type 加密方式(例如:使用騰訊qq郵箱時此處填ssl,不加密不填寫此項)
// @param $user 用戶名
// @param $pwd 密碼或授權碼
// @param $subject 郵件主題
// @param $body 郵件內容
// @param $from 郵件來自郵箱號
// @param $from_name 郵件來自名稱
// @param $to 收件人郵箱
public static function sendMail($to, $subject, $body, $encryption_type = null) {
$host = C('SMTP');
$port = C('MAIL_PORT');
$user = C('MAIL_USER');
$pwd = C('MAIL_PWD');
$from = C('MAIL_FROM');
$from_name = C('MAIL_FROM_NAME');
Vendor('swiftmailer.lib.swift_required');
$transport=\Swift_SmtpTransport::newInstance($host, $port, $encryption_type)
->setUsername($user)
->setPassword($pwd);
$mailer =\Swift_Mailer::newInstance($transport);
$message=\Swift_Message::newInstance()
->setSubject($subject)
->setFrom(array($from=>$from_name))
->setTo($to)
->setContentType("text/html")
->setBody($body);
$mailer->protocol='smtp';
$mailer->send($message);
}
}
控制器和方法(按需求確定位置)/Application/Home/Controller/IndexController.class.php
<?php
namespace Home\Controller;
use Think\Controller;
use Home\Common\Swiftmail;
class IndexController extends Controller {
public function mail_send() {
$to = '472323087@qq.com';
$subject = 'SwiftMail測試標題';
$body = '<h1>SwiftMail演示</h1>這是dee對SwiftMail的測試內容';
try {
Swiftmail::sendMail($to, $subject, $body);
echo 'success';
} catch(Swift_RfcComplianceException $e) {
echo $e->getMessage();
}
}
}
運行后顯示 success
收取郵件:
打開郵件:

