无法通过PHPMailer的联系表单发送电子邮件

时间:2016-08-19 13:48:21

标签: php email phpmailer

我在使用PHPMailer类发送电子邮件时遇到问题,在我提交表单后,此消息显示:“已发送消息”但我没有收到任何电子邮件,我甚至检查了垃圾邮件文件夹及其空。

这里是html表单代码:

<form action="<?php echo $PHP_SELF; ?>" method="post">

<input type="text" class="form-control" placeholder="Name" name="name">

<input type="email" class="form-control" placeholder="Email" name="email">

<input type="text" class="form-control" placeholder="Subject" name="subject">

<textarea class="form-control" placeholder="Message" rows="7" name="message">    </textarea>

<input type="submit" class="form-control" name="submit" value="submit">

</form>

和php代码是:

<?php
if(isset($_POST['email'])) {

     if(isset($_POST['subject'])){ $subject = $_POST['subject']; }
     if(isset($_POST['message'])){ $message = $_POST['message']; }
     if(isset($_POST['name'])){ $name = $_POST['name']; }
     if(isset($_POST['email'])){ $email = $_POST['email']; }

require_once('class.phpmailer.php');

$mail             = new PHPMailer(); 

$body             = $message;

$mail->SetFrom($email, $name);

$address = "example@domain.net";
$mail->AddAddress($address, "example@domain.net");

$mail->Subject    = $subject;

$mail->MsgHTML($body);

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}
}

?>

1 个答案:

答案 0 :(得分:0)

这是您的HTML代码

<form action="yourphpcode.php" method="post">

<input type="text" class="form-control" placeholder="Name" name="name">

<input type="email" class="form-control" placeholder="Email" name="email">

<input type="text" class="form-control" placeholder="Subject" name="subject">

<textarea class="form-control" placeholder="Message" rows="7" name="message">    </textarea>

<input type="submit" class="form-control" name="submit" value="submit">

</form>

这是您的PHP代码

<?php
if (isset($_POST['submit'])) {


    $subject = "subject : " . $_POST['subject'] . "<br>";
    $message = "message :" . $_POST['message'] . "<br>";
    $name    = "name :" . $_POST['name'] . "<br>";
    $email   = "email :" . $_POST['email'] . "<br>";

    $message = "
 \n $subject \n 
 \n $message \n  
 \n $name \n 
 \n $email \n 

";
    echo $message;

    include "PHPMailer_5.2.4/class.phpmailer.php";

    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';

    $mail->SMTPAuth   = true;
    $mail->Username   = 'yourgmail@gmail.com';
    $mail->Password   = 'password';
    $mail->SMTPSecure = 'tls';
    $mail->Port       = 587;
    $mail->setFrom('someaddress@example.com', 'Mailer');
    $mail->addAddress('someaddress@example.com', 'Test Name');
    $mail->addAttachment('fileaddress');
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = $message;
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if (!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }
}

?>

试试这个工作正常.. !!