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条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分