php调用发邮件,phpmail 的调用(发邮件例子)
时间: 2023-08-21 19:05:04 浏览: 62
好的,以下是一个使用 PHPMailer 库发送邮件的示例:
```php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// 引入 PHPMailer 库
require 'vendor/autoload.php';
// 实例化 PHPMailer 对象
$mail = new PHPMailer(true); // true 表示开启异常处理
try {
// 配置 SMTP 服务器
$mail->SMTPDebug = 0; // 调试:0 关闭,1 开启
$mail->isSMTP();
$mail->Host = 'smtp.163.com'; // SMTP 服务器地址
$mail->SMTPAuth = true;
$mail->Username = 'sender@example.com'; // SMTP 登录账号
$mail->Password = 'password'; // SMTP 登录密码
$mail->SMTPSecure = 'ssl'; // 邮件传输协议
$mail->Port = 465; // SMTP 端口号
// 设置发件人、收件人、邮件主题、内容
$mail->setFrom('sender@example.com', 'Sender');
$mail->addAddress('recipient@example.com', 'Recipient');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email from PHPMailer.';
// 发送邮件
$mail->send();
echo 'Email sent successfully.';
} catch (Exception $e) {
echo 'Email could not be sent. Error message: ', $mail->ErrorInfo;
}
```
注意,在使用这个示例之前,需要先使用 Composer 安装 PHPMailer 库,命令如下:
```
composer require phpmailer/phpmailer
```
另外,上面的示例使用了 163 邮箱作为 SMTP 服务器,如果你使用的是其他邮箱,需要更改相关配置。