PHP发送邮件主要通过SMTP(Simple Mail Transfer Protocol)协议实现。SMTP是一种用于传输电子邮件的协议,它定义了邮件服务器之间交换邮件的格式和过程。
mail()
函数。<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// 邮件服务器设置
$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元无门槛券
手把手带您无忧上云