将SMTP Gmail身份验证添加到PHP Mailer联系表单

时间:2014-12-21 16:04:23

标签: php email smtp phpmailer

我有一个有效的PHP电子邮件表单,大约有10%的时间可以使用。我需要添加身份验证才能使其在100%的时间内正常工作,但我正在尝试使用PHPMailer(https://github.com/PHPMailer/PHPMailer)并且遇到错误而无法使其正常工作。

我的基本工作脚本没有身份验证:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Oops! There was a problem with your message. Please check that all fields are filled in.";
        exit;
    }

    $recipient = "myaddress@gmail.co";
    $subject = "Enquiry from $name";
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";
    $email_headers = "From: Enquiry <myenquiry@gmail.co>";

    if (mail($recipient, $subject, $email_content, $email_headers)) {
        echo "Thank You! Your message has been sent.";
    } else {
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

} 
else {
    echo "There was a problem with your submission, please try again.";
}

?>

任何帮助将不胜感激!

非常感谢。

2 个答案:

答案 0 :(得分:1)

您不在代码中使用PHPMailer 通过作曲家https://packagist.org/packages/phpmailer/phpmailer

获取PHPMailer

我在15分钟前试过它,100%的时间对我都很好(我只尝试了20次) 代码:

$mail = new PHPMailer(); 

       $mail->IsSMTP();
       $mail->SMTPAuth = true;
       $mail->SMTPSecure = 'ssl';
       $mail->Host = 'smtp.gmail.com';
       $mail->Port = 465;
       $mail->Username = "email@gmail.com";
       $mail->Password = "ur pass";

       $mail->ChartSet = 'utf-8';
       $mail->From     = 'me';
       $mail->Subject  = "subject here";
       $mail->AddAddress( 'email@gmail.com' ); //to
       $mail->MsgHTML( $body );
       $mail->IsHTML( true );
       $mail->IsSMTP();

       $mail->send();
祝你好运。

答案 1 :(得分:-2)

从这段代码看,你看起来好像在使用PHP的内置mail()函数,而不是phpmailer。如果您使用的是phpmailer,则应该有一行创建一个新的PHPMailer对象,例如:$mail = new PHPMailer;。有关如何使用PHPMailer通过Gmail的SMTP服务器(smtp.gmail.com)通过身份验证发送消息的示例,请参阅http://phpmailer.worxware.com/?pg=examplebgmail