回复发件人 - PHP电子邮件

7

这是我用于电子邮件表单的代码。它可以很好地工作,并将邮件发送到我的邮箱。但是,我该如何使自己能够回复从表单接收到的电子邮件呢?您能否编辑我的代码并将其放入其中,因为我是一个非常新手的php程序员。非常感谢!

<?php

$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "adamgoredesign@gmail.com";

mail ($to, $subject, $message, "From: " . $name);

header('Location: contact_thankyou.html');

?>

1
此代码容易受到SMTP头部注入攻击,因为POST字段“name”未经过清理。 - php_coder_3809625
1个回答

31

您需要设置headers以便通过发件人电子邮件:

例如:

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

所以你的代码应该长这样:

$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "adamgoredesign@gmail.com";
$headers = 'From: '.$email."\r\n" .
        'Reply-To: '.$email."\r\n" .
        'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

header('Location: contact_thankyou.html');

注意:我从未亲自测试过这个,我通常使用smtp.mail类来完成所有这些工作,因为它更容易、更干净...去看看吧...

然后它会看起来像这样:

<?php
require 'class.phpmailer.php';

$mail = new PHPMailer;

$mail->IsSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup server
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'jswan';                            // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

$mail->From = 'from@example.com';
$mail->FromName = 'Mailer';
$mail->AddAddress('josh@example.net', 'Josh Adams');  // Add a recipient
$mail->AddAddress('ellen@example.com');               // Name is optional
$mail->AddReplyTo('info@example.com', 'Information');
$mail->AddCC('cc@example.com');
$mail->AddBCC('bcc@example.com');

$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';

if(!$mail->Send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}

echo 'Message has been sent';

好的,我尝试了你的代码。但现在我的电子邮件根本无法发送。所以不确定出了什么问题。我宁愿不使用PHPmainer来完成这个,但感谢提供链接。 - Adam G
就是说,我根本没有收到邮件。 - Adam G
1
如果我省略最后一个参数(,"From: " . $name),这个只对我有效。 - dwitvliet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接