如何使用php mail()函数将联系表单消息发送到smtp服务器的电子邮件?

时间:2018-01-29 14:13:10

标签: php forms phpmailer

我的网页上有一个表单,来自联系表单的邮件会转到smtp服务器的电子邮件中。我已使用此代码发送消息:

require_once("PHPMailer-master/PHPMailerAutoload.php");

$fromName = $_POST['username'];
$fromEmail = $_POST['email'];
$theMessage = $_POST['message'];
$theSubject = $_POST['subject'];
$theCompany = $_POST['company'];
$thePhone = $_POST['phone'];
$isSuccess = 0;
$notificationMsg = "";

$mail = new PHPMailer;
// $mail->SMTPDebug = 3;

$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 465;

// Authentication
$mail->Username = 'smtp_username';
$mail->Password = 'smtp_password';

// Compose
$mail->SetFrom($fromEmail, $fromName);
$mail->addReplyTo($fromEmail, $fromName);

// Send To
$mail->addAddress('info@mycompany.com', 'My Company');

$mail->WordWrap = 50;
$mail->isHTML(true);

if ($mail->send()) {
   $isSuccess = 1;

   $notificationMsg = "Thank you for your message";
} else {
   $isSuccess = 0;

   $notificationMsg .= "Sorry, there is something wrong. Please, try again letter.";
   exit ;
}

echo $notificationMsg;

但是,它没有用。如果我为Compose部分添加这些行:

// Compose    
$mail->From = 'user@mycompany.com';  // any email address from our own

它会起作用!它显示在我们的电子邮箱中:

from: Root User <user@mycompany.com>
reply-to:   Sender Name <sender@gmail.com>
to: My Company <info@mycompany.com>

电子邮箱中的邮件正文是可以的。但是,代替sender's email地址,our email地址显示在form字段。此外,显示的是Root User,而不是sender's name。如果我在撰写部分再添加一行:

// Compose    
$mail->From = 'user@mycompany.com';  // any email address from our own
$mail->FromName = 'Anything';

然后显示:

from: Anything <user@mycompany.com>
reply-to:   Sender Name <sender@gmail.com>
to: My Company <info@mycompany.com>

甚至,我试过这个:

// Compose   
$mail->From = $fromEmail;
$mail->FromName = $fromName;

但是,消息已经发送,然后形成我的联系表格。

所以,对于撰写部分,

// Compose    
$mail->From = 'user@mycompany.com';  // any email address from our own
$mail->FromName = 'Anything';
$mail->SetFrom($fromEmail, $fromName);
$mail->addReplyTo($fromEmail, $fromName);

第3行似乎不起作用。但是,该行应该工作而不是前两行,在我们的电子邮箱中,应该显示:

from: Sender Name <sender@gmail.com>
reply-to: Sender Name <sender@gmail.com>
to: My Company <info@mycompany.com>

如何解决这个问题?提前谢谢。

1 个答案:

答案 0 :(得分:2)

请勿尝试使用提交者的地址作为发件人地址;它是伪造的,即使你可以随身携带它(看起来你无论如何也不能),它会导致你的消息无法通过SPF检查并被垃圾邮件过滤或退回。将您自己的地址放在来自地址和提交者的地址的回复中,如the contact form example provided with PHPMailer所示。

$mail->SMTPSecure = 'tls';$mail->Port = 465;的组合不起作用;将Port更改为587 SMTPSecure更改为ssl

阅读文档,根据PHPMailer提供的示例编写代码,并更新到最新版本。