dongrou5254 2014-12-21 16:04
浏览 38
已采纳

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

I have a working PHP email form that works about 10% of the time. I need to add authentication to make it work 100% of the time but I'm trying to use PHPMailer (https://github.com/PHPMailer/PHPMailer) and am getting errors and can't get it to work.

My basic working script without authentication:

<?php

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

    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
    $name = str_replace(array("","
"),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
";
    $email_content .= "Email: $email

";
    $email_content .= "Message:
$message
";
    $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.";
}

?>

Any help will be greatly appreciated!

Many thanks.

  • 写回答

2条回答 默认 最新

  • doudu2404 2014-12-22 10:58
    关注

    you don't use PHPMailer in your code to get PHPMailer by composer https://packagist.org/packages/phpmailer/phpmailer

    I tried it 15 minutes ago and it works fine for me 100% of the time (I tried only ~20 times) the code:

    $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();
    

    good luck.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了