如何注册腾讯企业邮箱
https://www.bilibili.com/video/av14351397/
如何在项目中使用
https://www.bilibili.com/video/av14351961/
下面是我自己在采坑的过程中遇到的问题
首先我们下载PHPMailer的,下载地址:https://github.com/PHPMailer/PHPMailer
将文件部入到我们的TP框架中,放到extend/org中。
第一步我们应该准备发送邮箱的账号,我这里用的是腾讯企业邮箱
没有的可以直接注册一个:https://exmail.qq.com
将类文件PHPMailer.php第1760行的方法里的if判断中添加include_once 'SMTP.php';
if (!is_object($this->smtp)) {
include_once 'SMTP.php';
$this->smtp=new SMTP();
}
在控制器里面代码
<?php
namespace app\index\controller;
use PHPMailer\PHPMailer\PHPMailer;
use think\Controller;
use think\Loader;
class Mailsms extends Controller {
//发送商,,,QQ企业邮箱地址都是smtp.exmail.qq.com
const HOST = 'smtp.163.com';
//发件人邮箱....企业邮箱中一个成员的账号
const USERNAME = 'dhrbes@163.com';
//发件箱授权码。。。。。。这里是成员账号的登录密码
const PASSWORD = '45613';
//发送模板
const TEMPLATE = '您的验证码是{code},请在10分钟内填写。';
//是否debug 测试环境使用
const DEBUG = false;
//实例
protected $mail;
public function _initialize() {
Loader::import("PHPMailer.src.Exception", EXTEND_PATH, ".php");
Loader::import("PHPMailer.src.PHPMailer", EXTEND_PATH, ".php");
Loader::import("PHPMailer.src.SMTP", EXTEND_PATH, ".php");
$this->mail = new PHPMailer();
}
public function index() {
$this->sendMail('73674611345864500@qq.com', '您有一封新消息', '2433242');
}
/**
* target 发送给谁 收件人的邮箱
* subject 主题
* code 验证码apiMailsms/index
*/
public function sendMail($target, $subject, $code) {
$content = str_replace('{code}', $code, self::TEMPLATE);
try {
$this->mail->SMTPDebug = self::DEBUG; //可以设置成false不输出
$this->mail->isSMTP();
$this->mail->Host = self::HOST; //服务器
$this->mail->SMTPAuth = true; //是否开启SMTP认证
$this->mail->Username = self::USERNAME; //发件人邮箱
$this->mail->Password = self::PASSWORD; //发件箱授权码
// $this->mail->SMTPSecure='tls';//启用TLS加密,' ssl '也接受
// $this->mail->Port='25';//端口 //注意使用阿里域名的需要使用ssl加密,465端口,
$this->mail->SMTPSecure = 'ssl'; //启用TLS加密,' ssl '也接受
$this->mail->Port = '465'; //端口
$this->mail->CharSet = 'UTF-8'; //设置邮件内容编码
$this->mail->setFrom(self::USERNAME); //发件人
//$this->mail->addAttachment('/var/tmp/file.tar.gz');//附件
//$this->mail->addAttachment('/tmp/image.jpg', 'new.jpg');//附件重命名
$this->mail->addAddress($target); //发送给谁
$this->mail->isHTML(true);
$this->mail->Subject = $subject;
$this->mail->Body = $content;
//$this->mail->AltBody ='This is the body in plain text for non-HTML mail clients';
if ($this->mail->send()) {
echo "发送成功!";
} else {
echo "发送失败!";
}
} catch (Exception $e) {
echo "异常抛出";
}
}
}