在 PHP 中发送电子邮件通常涉及使用内置的 mail
函数或使用更强大的邮件库,例如 PHPMailer 或 Swift Mailer。以下是使用 mail
函数和 PHPMailer 的基本示例:
使用 mail
函数:
<?php
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
// Additional headers
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "CC: cc@example.com\r\n";
$headers .= "BCC: bcc@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
// Send email
$mailSent = mail($to, $subject, $message, $headers);
if ($mailSent) {
echo "Email sent successfully.";
} else {
echo "Email delivery failed!";
}
?>
请注意,使用 mail
函数需要配置本地服务器上的邮件传输代理(MTA),例如 Sendmail 或 Postfix。
使用 PHPMailer:
首先,你需要下载并引入 PHPMailer 库。你可以从 PHPMailer 的 GitHub 页面 下载最新版本,并将其包含到你的项目中。
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
// Create a new PHPMailer instance
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_username';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Recipients
$mail->setFrom('sender@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// Content
$mail->isHTML(true);
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';
// Send email
$mail->send();
echo 'Email sent successfully.';
} catch (Exception $e) {
echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
在上述示例中,确保替换以下信息:
smtp.example.com
、your_username
和your_password
分别为你的 SMTP 服务器地址、用户名和密码。'sender@example.com'
和'recipient@example.com'
分别为发件人和收件人的电子邮件地址。
使用 PHPMailer 或类似的邮件库通常更加灵活,支持更多高级功能,例如附件、SMTP 验证等。选择邮件库还可以提高代码的可维护性和安全性。