从服务器PHP发送电子邮件

时间:2017-01-02 07:20:00

标签: php sendmail html-form-post

我在html文件中有一个表单,当用户填写表单并提交时,我正试图在我的Gmail帐户上收到电子邮件。我的网站运行在服务器上而不是本地主机上。我的代码没有错误,但仍然没有收到电子邮件。我不知道为什么?任何人都可以给我示例代码或告诉我我做错了什么? .. 提前致谢 ... 这是我的代码

<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
    <div class="row  wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="300ms">
      <div class="col-sm-6">
        <div class="form-group">
          <input type="text" name="name" class="form-control" placeholder="Name" required="required">
        </div>
      </div>
      <div class="col-sm-6">
        <div class="form-group">
          <input type="email" name="email" class="form-control" placeholder="Email Address" required="required">
        </div>
      </div>
    </div>
    <div class="form-group">
      <input type="text" name="subject" class="form-control" placeholder="Subject" required="required">
    </div>
    <div class="form-group">
      <textarea name="message" id="message" class="form-control" rows="4" placeholder="Enter your message" required="required"></textarea>
    </div>                        
    <div class="form-group">
      <button type="submit" class="btn-submit">Send Now</button>
    </div>
</form>   

而sendemail.php是

<?php 
$name = @trim(stripslashes($_POST['name']));
$from       = @trim(stripslashes($_POST['email'])); 
$subject    = @trim(stripslashes($_POST['subject'])); 
$message    = @trim(stripslashes($_POST['message'])); 
$to         = 'khurram.ansar@gmail.com';

$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

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

die; 

1 个答案:

答案 0 :(得分:1)

根据documentation

  

多个额外标题应与分开

所以你的php文件应该是:

<?php
$name = @trim(stripslashes($_POST['name']));
$from = @trim(stripslashes($_POST['email']));
$subject = @trim(stripslashes($_POST['subject']));
$message = @trim(stripslashes($_POST['message']));
$to = 'khurram.ansar@gmail.com';

$headers = "MIME-Version: 1.0" . "\r\n" .
        "Content-type: text/plain; charset=iso-8859-1" . "\r\n" .
        "From: {$name} <{$from}>" . "\r\n" .
        "Reply-To: <{$from}>" . "\r\n" .
        "Subject: {$subject}" . "\r\n" .
        "X-Mailer: PHP/" . phpversion();

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

die;
?>