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‘ => ‘[email protected]‘, //邮箱用户名 ‘MAIL_PWD‘ => ‘XXX‘, //发送邮箱密码或者授权码 ‘MAIL_FROM‘ => ‘[email protected]‘, ‘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 = ‘[email protected]‘; $subject = ‘SwiftMail测试标题‘; $body = ‘<h1>SwiftMail演示</h1>这是dee对SwiftMail的测试内容‘; try { Swiftmail::sendMail($to, $subject, $body); echo ‘success‘; } catch(Swift_RfcComplianceException $e) { echo $e->getMessage(); } } }
运行后显示 success
收取邮件:
打开邮件:
时间: 2024-10-11 13:00:08