<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = 'contact@yoursite.com';
$subject = 'Customer Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
我试着创建了一个简单的邮件表单。表单本身在我的index.html页面上,但它提交到一个单独的“感谢您的提交”页面thanks . PHP,其中嵌入了上述PHP代码。
代码完美地提交,但从未发送电子邮件。我该如何解决这个问题?
我有这个问题,并发现剥离标题帮助我获得邮件。
所以这个:
$headers = "MIME-Version: 1.0;\r\n";
$headers .= "Content-type: text/plain; charset=utf-8;\r\n";
$headers .= "To: ".$recipient."\r\n";
$headers .= "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";
成为这个:
$headers = "From: ".__SITE_TITLE."\r\n";
$headers .= "Reply-To: ".$sender."\r\n";
不需要To:标头。
邮件客户端非常擅长嗅出url并将其重写为超链接。所以我不需要编写HTML并在content-type头文件中指定text/ HTML。我只是在消息体中添加了带\r\n的新行。
我知道这不是编码纯粹主义者的方法,但它适用于我所需要的。
如果使用PHP发送邮件遇到问题,可以考虑使用PHPMailer或SwiftMailer等替代方案。
当我需要用PHP发送邮件时,我通常使用SwiftMailer。
基本用法:
require 'mail/swift_required.php';
$message = Swift_Message::newInstance()
// The subject of your email
->setSubject('Jane Doe sends you a message')
// The from address(es)
->setFrom(array('jane.doe@gmail.com' => 'Jane Doe'))
// The to address(es)
->setTo(array('frank.stevens@gmail.com' => 'Frank Stevens'))
// Here, you put the content of your email
->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
echo json_encode([
"status" => "OK",
"message" => 'Your message has been sent!'
], JSON_PRETTY_PRINT);
} else {
echo json_encode([
"status" => "error",
"message" => 'Oops! Something went wrong!'
], JSON_PRETTY_PRINT);
}
有关如何使用SwiftMailer的更多信息,请参阅官方文档。
我觉得这个应该能搞定。我只是添加了一个if(isset,并在主体中的变量中添加了连接,以将PHP与HTML分开。
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = 'contact@yoursite.com';
$subject = 'Customer Inquiry';
$body = "From:" .$name."\r\n E-Mail:" .$email."\r\n Message:\r\n" .$message;
if (isset($_POST['submit']))
{
if (mail ($to, $subject, $body, $from))
{
echo '<p>Your message has been sent!</p>';
}
else
{
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>