要给新项目写一个注册功能,邮件认证是必须的,那就必须发邮件验证码
先是使用打乱数组制造验证码
/**
* 获得随机字符串
* @param $len 需要的长度
* @param $special 是否需要特殊符号
* @return string 返回随机字符串
*/
function getRandomStr($len, $special=true){
$chars = array(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
"3", "4", "5", "6", "7", "8", "9"
);
if($special){
$chars = array_merge($chars, array(
"!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
"%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
"}", "<", ">", "~", "+", "=", ",", "."
));
}
$charsLen = count($chars) - 1;
shuffle($chars); //打乱数组顺序
$str = '';
for($i=0; $i<$len; $i++){
$str .= $chars[mt_rand(0, $charsLen)]; //随机取出一位
}
return $str;
}
调用函数只需要传返回字符串的长度即可
然后去了PHPMailer的官网试图安装PHPMailer/PHPMailer:PHP 的经典电子邮件发送库
然后发现需要Composer,我没有安装Composer,然后又去了Composer中文网
通过了全局安装Composer之后就可以了用composer命令了
下面安装PHPMailer
composer require phpmailer/phpmailer
然后在安装的根目录创建一个.php文件,写入以下示例代码
<?php
//将PHPMailer类导入全局命名空间
//这些必须在脚本的顶部,而不是在函数内部
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//加载 Composer 的自动加载器
require 'vendor/autoload.php';
//创建一个实例; 传递 `true` 启用异常
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //启用详细调试输出
$mail->isSMTP(); //使用SMTP发送
$mail->Host = 'smtp.example.com'; //设置SMTP服务器发送通过
$mail->SMTPAuth = true; //启用SMTP认证
$mail->Username = 'user@example.com'; //SMTP用户名
$mail->Password = 'secret'; //SMTP密码
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //启用隐式TLS加密
$mail->Port = 465; //要连接的TCP端口; 如果您设置了 `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`,请使用 587
//收件人
$mail->setFrom('from@example.com', 'Mailer'); //发件人
$mail->addAddress('joe@example.net', 'Joe User'); //添加收件人
//$mail->addAddress('ellen@example.com'); //名字是可选的
$mail->addReplyTo('info@example.com', 'Information'); //添加回复到
//$mail->addCC('cc@example.com'); //添加CC
//$mail->addBCC('bcc@example.com'); //添加密件抄送
/*附件
$mail->addAttachment('/var/tmp/file.tar.gz'); //添加附件
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //可选的,附件名称
*/
//内容
$mail->isHTML(true); //设置邮件格式为HTML
$mail->Subject = 'Here is the subject'; //主题
$mail->Body = 'This is the HTML message body <b>in bold!</b>'; //内容
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; //这是非 HTML 邮件客户端的纯文本正文
$mail->send();
echo '信息已发送';
} catch (Exception $e) {
echo "无法发送消息。 邮件错误: {$mail->ErrorInfo}";
}
填写了信息应该就可以了