PHPMailer 收到电子邮件时地址错误

PHPMailer wrong from address when receiving email

我遇到了这个问题,当我收到一封从我的本地主机网站发送的电子邮件时,我得到的发件人部分错误的电子邮件地址 ($mail->SetFrom($email, $name)). 我有自己的电子邮件地址作为发件人,而不是在我网站的文本框中输入的地址。

我到处寻找一些答案,遗憾的是没有任何效果。我已尝试继续 Chrome 帐户设置并将安全性较低的应用程序设置为开启。那没有用。

我尝试了多种设置 SetFrom 电子邮件和名称的方法。需要帮助!

<?php 
$dir = __DIR__;
require_once("$dir/../PHPMailer-master/PHPMailerAutoload.php");
extract($_POST, EXTR_PREFIX_ALL, "P");

$name = $_POST['postName'];
$email = $_POST['postEmail'];
$subject = $_POST['postSubject'];
$message = $_POST['postMessage'];
$file = $_POST['postFile'];

echo "Name: ".$_POST['postName'];
echo "\n";
echo "Email: ".$_POST['postEmail'];
echo "\n";
echo "Subject: ".$_POST['postSubject'];
echo "\n";
echo "Message: ".$_POST['postMessage'];
echo "\n";
echo "File: ".$_POST['postFile'];

$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "mail.gmail.com"; // SMTP server
//$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "tls";                 // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 587;                   // set the SMTP port for the GMAIL server
$mail->Username   = "xxxx@gmail.com";  // GMAIL username
$mail->Password   = "xxxx";            // GMAIL password
$mail->SetFrom($email, $name);
$mail->AddReplyTo($email, $name);
$mail->addAddress("xxxx@gmail.com", "name");
$mail->AddAttachment("$file");
$mail->Subject   = "$subject";
$mail->Body      = "$message";

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
} ?>

这是我设置的警报,显示发送到我的 PHP 脚本的所有 POST 参数。所有 POST 变量都在那里。 唯一的问题是 SetFrom($email, $name)

Javascript Alert with POST Parameters

Gmail 不允许您设置任意发件人地址,但您可以定义预设别名。

但是,无论如何您都不应该尝试这样做。将 user-provided 值放在发件人地址中是一个非常糟糕的主意,因为您的邮件将无法通过 SPF 检查,因为它是伪造的。将您自己的地址放在发件人地址(以及收件人地址)中,并使用 addReplyTo() 方法将提交者的地址放在 reply-to header 中。您可以在 PHPMailer 提供的联系表单示例中看到它的工作原理:

//Use a fixed address in your own domain as the from address
//**DO NOT** use the submitter's address here as it will be forgery
//and will cause your messages to fail SPF checks
$mail->setFrom('from@example.com', 'First Last');
//Send the message to yourself, or whoever should receive contact for submissions
$mail->addAddress('whoto@example.com', 'John Doe');
//Put the submitter's address in a reply-to header
//This will fail if the address provided is invalid,
//in which case we should ignore the whole request
if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
...