PHP发送邮件通常使用SMTP(Simple Mail Transfer Protocol)协议。SMTP是一种用于发送电子邮件的协议,PHP提供了多种库来支持SMTP邮件发送,如PHPMailer、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.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发送邮件失败的问题。如果问题依然存在,建议查看SMTP服务器的日志,以获取更多详细的错误信息。
领取专属 10元无门槛券
手把手带您无忧上云