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


Add SMTP Gmail authentication to PHP Mailer contact form

我有一个有效的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.";
}
?>

任何帮助将不胜感激!

非常感谢。

你没有在代码中使用PHPMailer。通过作曲家获得PHPMailer https://packagist.org/packages/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();

祝你好运。

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