使用php发送电子邮件

时间:2017-05-01 08:10:22

标签: php

我正在尝试使用php发送电子邮件,但是当我在浏览器上尝试时,我收到错误:

  

“服务器无法发送消息。请稍后再试。”

这是我的php文件

<?php
if( isset($_GET['n']) && isset($_GET['e']) && isset($_GET['m']) ){
        $n = $_GET['n']; // HINT: use preg_replace() to filter the data
        $e = $_GET['e'];
        $m = nl2br($_GET['m']);
        $to = "amal.soltni@esprit.tn";
        $from = $e;
        $subject = 'Contact Form Message';
        $message = '<b>Name:</b> '.$n.' <br><b>Email:</b> '.$e.' <p>'.$m.'</p>';
        $headers = "From: $from\n";
        $headers .= "MIME-Version: 1.0\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\n";
        if( mail($to, $subject, $message, $headers) ){
                echo "success";
        } else {
                echo "The server failed to send the message. Please try again later.";
        }
}
?>

2 个答案:

答案 0 :(得分:1)

尝试这个发送邮件并使用实时服务器执行此代码,不要使用localhost发送邮件

    <?php
    if( isset($_GET['n']) && isset($_GET['e']) && isset($_GET['m']) ){
    $n = $_GET['n']; 
    $e = $_GET['e'];
    $m = nl2br($_GET['m']);
    $to = "amal.soltni@esprit.tn";
    $from = $e;
    $subject = "My subject";
    $message = '<b>Name:</b> '.$n.' <br><b>Email:</b> '.$e.' <p>'.$m.'</p>';;
    $headers = 'From: .$from.' . '\r\n' .
    $send = mail($to,$subject,$message,$headers);
   }else {
      echo "The server failed to send the message. Please try again later.";
    }
    ?>

答案 1 :(得分:-1)

请使用以下代码。

   <?php
        if (isset($_POST["submit"]))
    {
        $n = $_POST['n'];
        $e = $_POST['e'];
        $m = $_POST['m'];
        $to = "amal.soltni@esprit.tn";
        $from = $e;
        $subject = 'Contact Form Message';
        $message = '<b>Name:</b> '.$n.' <br><b>Email:</b> '.$e.' <p>'.$m.'</p>';
        $headers = "From: $from\n";
        $headers .= "MIME-Version: 1.0\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\n";
        if( mail($to, $subject, $message, $headers) ){
                echo "success";
        } else {
                echo "The server failed to send the message. Please try again later.";
        }
    }

  ?>

  <form method="post" >
  <input type="text" name="n" placeholder="Name"><br>
  <input type="email" name="e" placeholder="Email"><br>
  <textarea col="10" rows="5"  name="m" placeholder="Message"></textarea><br>
  <input type="submit" name="submit">
  </form>