📜  smtp php 测试 - PHP (1)

📅  最后修改于: 2023-12-03 15:20:09.948000             🧑  作者: Mango

SMTP PHP 测试 - PHP

简介

SMTP(Simple Mail Transfer Protocol)是一种用于发送邮件的标准协议,在 PHP 中通过 SMTP 协议发送邮件可以使用 PHPMailerSwiftMailer 等第三方库。使用这些库可以给我们提供一个比较稳健的邮件发送方案。

安装

使用 Composer 安装 PHPMailer:

composer require phpmailer/phpmailer

使用 Composer 安装 SwiftMailer:

composer require swiftmailer/swiftmailer
使用 PHPMailer 发送邮件
<?php

require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    // SMTP 配置
    $mail->isSMTP();
    $mail->Host = 'smtp.qq.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'sender@qq.com';
    $mail->Password = 'password';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // 邮件配置
    $mail->setFrom('sender@qq.com', 'Sender');
    $mail->addAddress('recipient@example.com', 'Recipient');

    $mail->isHTML(true);
    $mail->Subject = '邮件主题';
    $mail->Body = '邮件内容';

    $mail->send();
    echo '邮件发送成功!';
} catch (Exception $e) {
    echo '邮件发送失败: ', $mail->ErrorInfo;
}
使用 SwiftMailer 发送邮件
<?php

require 'vendor/autoload.php';

use Swift_SmtpTransport;
use Swift_Mailer;
use Swift_Message;

// 创建 transport 实例
$transport = (new Swift_SmtpTransport('smtp.qq.com', 465, 'ssl'))
    ->setUsername('sender@qq.com')
    ->setPassword('password');

// 创建 mailer 实例
$mailer = new Swift_Mailer($transport);

// 创建 message 实例
$message = (new Swift_Message('邮件主题'))
    ->setFrom(['sender@qq.com' => 'Sender'])
    ->setTo(['recipient@example.com' => 'Recipient'])
    ->setBody('邮件内容', 'text/html');

// 发送邮件
$result = $mailer->send($message);

if ($result) {
    echo '邮件发送成功!';
} else {
    echo '邮件发送失败!';
}

以上就是使用 PHPMailer 和 SwiftMailer 发送邮件的基本操作。如果需要更加详细的配置,可以去官方文档查看。