PHP发送邮件通常涉及到SMTP(Simple Mail Transfer Protocol)协议,它是一种用于传输电子邮件的标准协议。PHP提供了多种方式来发送邮件,包括使用内置的mail()
函数、PHPMailer库、SwiftMailer库等。
mail()
,同时也支持第三方库来处理复杂的邮件发送需求。mail()
函数:简单易用,但功能有限。<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user@example.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
// Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Joe User'); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$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}";
}
?>
From
、Reply-To
等。通过以上步骤和示例代码,你应该能够成功地在PHP中发送邮件。如果遇到具体问题,可以根据错误信息进行排查和解决。
领取专属 10元无门槛券
手把手带您无忧上云