| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <?php
- namespace App\Servers\Email;
- use Illuminate\Bus\Queueable;
- use Illuminate\Mail\Mailable;
- use Illuminate\Queue\SerializesModels;
- use Swift_Mailer;
- use Swift_Message;
- use Swift_SmtpTransport;
- /**
- * 邮件验证码发送
- * @author 唐远望
- * @version 1.0
- * @date 2026-03-30
- *
- */
- class VerifyCode extends Mailable
- {
- use Queueable, SerializesModels;
- /**
- * 封装SMTP发送邮件的方法
- *
- * @param string|array $to 收件人邮箱
- * @param string $subject 邮件主题
- * @param string $body 邮件内容
- * @param string|null $from 发件人邮箱,默认为配置中的from地址
- * @return int 发送结果
- */
- public static function sendSmtpEmail($to, $subject, $body, $from = null)
- {
- // 创建SMTP传输
- $transport = new Swift_SmtpTransport(
- config('mail.mailers.smtp.host'),
- config('mail.mailers.smtp.port')
- );
- // 设置认证信息
- $transport->setUsername(config('mail.mailers.smtp.username'));
- $transport->setPassword(config('mail.mailers.smtp.password'));
- // 设置加密方式
- if (config('mail.mailers.smtp.encryption')) {
- $transport->setEncryption(config('mail.mailers.smtp.encryption'));
- }
- // 创建邮件器
- $mailer = new Swift_Mailer($transport);
- // 创建邮件消息
- $message = new Swift_Message($subject);
- $message->setFrom($from ?: config('mail.from.address'));
- $message->setTo($to);
- // 自动识别 body 是否为 HTML 内容
- if (self::isHtmlContent($body)) {
- // HTML 内容
- $message->setBody($body, 'text/html');
- // 可选:同时添加纯文本版本作为备选
- $message->addPart(strip_tags($body), 'text/plain');
- } else {
- // 纯文本内容
- $message->setBody($body);
- }
- // 发送邮件
- return $mailer->send($message);
- }
- /**
- * 判断内容是否为 HTML
- *
- * @param string $content
- * @return bool
- */
- private static function isHtmlContent($content)
- {
- // 方法1:检查是否包含 HTML 标签
- if (strip_tags($content) != $content) {
- return true;
- }
- // 方法2:检查是否以 <!DOCTYPE html 或 <html 开头(忽略空白字符)
- $trimmedContent = trim($content);
- if (
- strpos($trimmedContent, '<!DOCTYPE html') === 0 ||
- strpos($trimmedContent, '<html') === 0
- ) {
- return true;
- }
- // 方法3:检查常见的 HTML 标签
- $htmlPatterns = [
- '/<div[^>]*>/i',
- '/<p[^>]*>/i',
- '/<span[^>]*>/i',
- '/<table[^>]*>/i',
- '/<br\s*\/?>/i',
- '/<h[1-6][^>]*>/i',
- '/<a[^>]*>/i',
- '/<img[^>]*>/i',
- '/<ul[^>]*>/i',
- '/<ol[^>]*>/i',
- '/<li[^>]*>/i'
- ];
- foreach ($htmlPatterns as $pattern) {
- if (preg_match($pattern, $content)) {
- return true;
- }
- }
- return false;
- }
- }
|