php邮件发送比较简单,这里整理了一下,方便小伙伴们收藏后直接开箱即用,当然,如果需要更复杂的配置,可以参考官网文档。
准备工作
下载对应的依赖包
1
| composer require phpmailer/phpmailer
|
代码封装与实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| <?php
namespace app\services;
use PHPMailer\PHPMailer\PHPMailer; use think\facade\Log;
class MailServer { private static string $host = ""; private static string $username = ""; private static string $smtp_password = ""; private static int $port = 587; private static string $addresser = ""; private static array $recover_mails = [];
public static function send($mail_subject, $content, string $recover_name = ""): array { $mail = new PHPMailer(true); try { $mail->SMTPDebug = 0; $mail->isSMTP(); $mail->Host = self::$host; $mail->SMTPAuth = true; $mail->Username = self::$username; $mail->Password = self::$smtp_password; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = self::$port;
$mail->setFrom(self::$username, self::$addresser); foreach (self::$recover_mails as $mail_add) { $mail->addAddress($mail_add, $recover_name); } $mail->isHTML(true); $mail->CharSet = "utf-8"; $mail->Subject = $mail_subject; $mail->Body = $content . " 【remote_phone】";
if (!$mail->send()) { return [false, "mail send fail:".$mail->ErrorInfo]; } else { return [true, "mail send success"]; } } catch (\Exception $e) { Log::error("邮件发送失败:".$e->getMessage()); return [false, "mail send exception:".$e->getMessage()]; } } }
|