📜  如何在 php 中自动发送邮件(1)

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

如何在 PHP 中自动发送邮件

在 PHP 中,发送邮件是一项常见的任务。无论是在网站注册之后发送欢迎邮件,还是在用户提交表单时发送通知邮件,都需要进行邮件发送操作。本文将介绍如何在 PHP 中自动发送邮件。

PHP 发送邮件的方法

PHP 发送邮件的方法有多种,包括使用内置函数 mail()、PHPMailer 类、swiftmailer 类等等。本文介绍使用 PHPMailer 类进行邮件发送。

PHPMailer 类

PHPMailer 是一种用于发送电子邮件的 PHP 类,支持 SMTP 服务器和 PHP mail() 函数发送邮件。它支持邮件消息的 HTML 和 plaintext,SMTP 封装和附件。PHPMailer 稳定可靠,广泛用于各种大小的项目。

可以使用 Composer 安装 PHPMailer。在命令行中运行以下命令:

composer require phpmailer/phpmailer
发送邮件的步骤
1. 引入 PHPMailer 类

在 PHP 文件中引入 PHPMailer 类。

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

require 'vendor/autoload.php';
2. 实例化 PHPMailer 类并进行基础配置

实例化 PHPMailer 类,并进行基础配置,如设置发送邮件的地址、设置邮件的发送方式等。

$mail = new PHPMailer(true);

// 设置发送邮件的地址
$mail->setFrom('sender@example.com', 'Sender Name');

// 设置邮件的接收者
$mail->addAddress('recipient@example.com', 'Recipient Name');

// 设置邮件的主题和正文
$mail->Subject = 'Test Email';
$mail->Body    = 'This is a test email.';

// 设置邮件发送方式
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'gmail_username@gmail.com';
$mail->Password = 'gmail_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
3. 发送邮件

调用 PHPMailer 类中的 send() 方法发送邮件。

$mail->send();
完整示例代码
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// 实例化 PHPMailer 类
$mail = new PHPMailer(true);

try {
    // 设置发送邮件的地址
    $mail->setFrom('sender@example.com', 'Sender Name');

    // 设置邮件的接收者
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // 设置邮件的主题和正文
    $mail->Subject = 'Test Email';
    $mail->Body    = 'This is a test email.';

    // 设置邮件发送方式
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'gmail_username@gmail.com';
    $mail->Password = 'gmail_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    // 发送邮件
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Error: ', $mail->ErrorInfo;
}

以上就是使用 PHPMailer 在 PHP 中发送邮件的基本步骤,根据实际情况可以进行更详细的配置,如添加附件、使用 SMTP 服务器等等。在使用 PHP 发送邮件时,建议使用 PHPMailer 类以确保邮件发送的稳定性和可靠性。