在ThinkPHP框架中,可以使用PHPMailer组件进行邮件发送。首先需要在composer.json中添加phpmailer的依赖:
{
"require": {
"phpmailer/phpmailer": "^6.5"
}
}
然后执行composer install
安装依赖。
接下来,在控制器中可以使用以下代码进行邮件发送:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class UserController extends Controller
{
public function sendEmail()
{
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@example.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('johndoe@example.com', 'John Doe');
$mail->addReplyTo('replyto@example.com', 'Reply-to');
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the plain text version of the message body.';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
}
其中,需要替换掉主机名、用户名、密码等信息。
对于短信验证码验证,可以使用阿里云的短信服务。需要在composer.json中添加阿里云SDK的依赖:
{
"require": {
"aliyuncs/sdk-core": "^1.14",
"aliyuncs/dysmsapi": "^1.1"
}
}
然后执行composer install
安装依赖。
接下来,在控制器中可以使用以下代码进行短信验证码验证:
use Aliyun\Core\Config;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
class UserController extends Controller
{
public function sendSms()
{
Config::load(); // 加载配置文件
$profile = DefaultProfile::getProfile('cn-hangzhou', '<accessKeyId>', '<accessSecret>');
$client = new DefaultAcsClient($profile);
$request = new SendSmsRequest();
$request->setPhoneNumbers('13000000000');
$request->setSignName('阿里云短信测试专用');
$request->setTemplateCode('SMS_0000001');
$request->setTemplateParam(json_encode(array(
'code' => '12345'
)));
$response = $client->getAcsResponse($request);
if ($response->Code == 'OK') {
echo '短信发送成功';
} else {
echo '短信发送失败:' . $response->Message;
}
}
}
其中,需要替换掉accessKeyId、accessSecret、以及短信模板代码等信息。同时需要在阿里云控制台中开通短信服务并获取相应的配置信息。