ThinkPHP 3.2.3 使用 Swift Mailer 邮件系统发送邮件
转自:http://www.cnblogs.com/dee0912/p/5451564.html#3443851
ThinkPHP 3.2.3 使用 Swift Mailer 邮件系统发送邮件
SwiftMailer 下载地址:https://github.com/swiftmailer/swiftmailer
版本:swiftmailer-5.x
把压缩包解压到 /ThinkPHP/Library/Vendor 中。
配置文件 config.php
1
2
3
4
5
6
7
8
9
10
11
|
<?php
return array (
//'配置项'=>'配置值'
//
邮件配置
'SMTP' => 'smtp.XXX.cn' ,
'MAIL_PORT' =>
25,
'MAIL_PWD' => 'XXX' , //发送邮箱密码或者授权码
'MAIL_FROM_NAME' => 'dee' ,
);
|
/Application/Home/Common/Swiftmail.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?php
namespace Home\Controller;
use Think\Controller;
use Home\Common\Swiftmail;
class IndexController extends Controller
{
public function mail_send()
{
$subject = 'SwiftMail测试标题' ;
$body = '<h1>SwiftMail演示</h1>这是dee对SwiftMail的测试内容' ;
try {
Swiftmail::sendMail( $to , $subject , $body );
echo 'success' ;
} catch (Swift_RfcComplianceException $e )
{
echo $e ->getMessage();
}
}
}
|
运行后显示 success
收取邮件:
打开邮件: