PHP发送邮件通常涉及使用SMTP(Simple Mail Transfer Protocol)协议。SMTP是一种用于在邮件服务器之间传输邮件的标准协议。PHP提供了多种方式来发送邮件,最常见的是使用PHP内置的mail()
函数或者使用第三方库如PHPMailer。
mail()
函数。<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// SMTP服务器设置
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// 发件人
$mail->setFrom('from@example.com', 'Mailer');
// 收件人
$mail->addAddress('recipient@example.com', 'Joe User');
// 邮件内容
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
通过以上步骤和示例代码,你可以实现PHP发送邮件的功能,并解决常见的邮件发送问题。
领取专属 10元无门槛券
手把手带您无忧上云