<?php
// 收件人的电子邮件地址
$to = "recipient@example.com";
// 主题
$subject = "Test Email";
// 邮件内容
$message = "This is a test email from PHP.";
// 附加邮件头
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "Content-type: text/html\r\n";
// 使用mail()函数发送电子邮件
$mailSent = mail($to, $subject, $message, $headers);
// 检查是否发送成功
if ($mailSent) {
echo "Email sent successfully.";
} else {
echo "Error sending email.";
}
?>
在上述例子中:
- $to 变量包含收件人的电子邮件地址。
- $subject 变量包含邮件主题。
- $message 变量包含邮件内容。
- $headers 变量包含附加的邮件头,其中设置了发件人、回复地址以及邮件内容的类型。
请注意:
- mail() 函数依赖于服务器的邮件配置。确保你的服务器配置允许使用 mail() 函数发送邮件。
- 由于 mail() 函数的一些限制,它可能不适用于所有情况,特别是在共享主机环境中。
- 在实际应用中,你可能更愿意使用专业的邮件库,如PHPMailer或Swift Mailer,它们提供更多功能和更好的错误处理。
下面是一个使用PHPMailer的简单示例:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php'; // 使用Composer加载PHPMailer
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF; // 开启调试模式
$mail->isSMTP(); // 使用SMTP
$mail->Host = 'smtp.example.com'; // SMTP服务器地址
$mail->SMTPAuth = true; // 启用SMTP身份验证
$mail->Username = 'your_username'; // SMTP用户名
$mail->Password = 'your_password'; // SMTP密码
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 启用TLS加密
$mail->Port = 587; // SMTP端口
//Recipients
$mail->setFrom('sender@example.com', 'Sender Name'); // 发件人地址和姓名
$mail->addAddress('recipient@example.com', 'Recipient Name'); // 收件人地址和姓名
//Content
$mail->isHTML(true); // 设置邮件格式为HTML
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email from PHPMailer.';
$mail->send();
echo 'Email sent successfully.';
} catch (Exception $e) {
echo "Error sending email: {$mail->ErrorInfo}";
}
?>
在使用这些库之前,你需要安装它们。使用Composer可以方便地安装PHPMailer:
composer require phpmailer/phpmailer
然后,你可以将上述代码保存到一个PHP文件中,并运行它来发送邮件。确保替换示例中的邮件服务器、用户名、密码和其他参数为你实际的邮件配置。
转载请注明出处:http://www.zyzy.cn/article/detail/3427/PHP