【问题标题】:PHP mail not showing senders email in from header frfom HTML formPHP邮件未显示来自标头frform HTML表单的发件人电子邮件
【发布时间】:2021-01-21 17:34:41
【问题描述】:

请有人帮助我在电子邮件的发件人标题中显示发件人电子邮件。请参阅下面的代码,目前当我收到电子邮件时,它会在 from 和 to 中显示收件人电子邮件地址。

HTML:

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

PHP:

<?php 
if(isset($_POST['submit'])){
    $to = "bestwayhomemaintenance@gmail.com"; 
    $from = $_POST['email']; 
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    //$headers = "From:" . $from;
    $headers = "From: $to \r\n";
    $headers .= "Reply-To: $from \r\n";
    //$headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    //mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    
    }
?>

【问题讨论】:

    标签: php email phpmailer


    【解决方案1】:

    除非您通过 gmail 的服务器发送,否则您不能从 gmail 地址发送,这实质上意味着您不能使用 PHP 的 mail() 函数来执行此操作。您或许可以尝试,但您的邮件将被标记为伪造。

    要使用邮件功能设置信封发件人,需要在邮件功能的$additional_params参数中使用-f参数。

    您的脚本容易受到标头注入攻击,并且还可以用于跨站点脚本。

    为避免伪造问题,我建议直接通过 gmail 发送,这意味着您需要使用 SMTP,而最简单的方法是发送至您标记此问题的 use PHPMailer。将您的代码基于随附的示例。

    【讨论】:

    • 感谢您的回复,只是为了澄清一下,当使用 PHPMailer 时,它会在电子邮件 From 标题中显示他们在 html 表单中输入的用户电子邮件地址吗?
    • 我已经下载了composer,我还需要github文件吗?如果我这样做了,下载后我应该把它们保存在哪里?
    • 您不能将提交者的地址作为发件人地址——这是会导致交付问题的伪造。在联系表单中解决此问题的常用方法是将您自己的地址放在“发件人”地址中,但将提交者的地址添加到“回复”中 - 请参阅the contact form example
    • composer 是一个安装在自己系统上的工具,它会下载依赖项(例如 PHPMailer)并创建一个自动加载器,这样您就不必担心自己加载文件。当您运行composer require phpmailer/phpmailer 时,composer 会将 PHPMailer 下载到vendor 文件夹中。然后在你的脚本中require 'vendor/autoload.php',它会根据需要自动加载 PHPMailer 文件。然后,您可以将全部内容上传到您的托管服务器——您不必在服务器上运行 composer。
    • 我正在使用您的代码,但它给了我错误“抱歉,出了点问题。请稍后再试。”可能出了什么问题?我应该去哪里看?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2011-10-07
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多