(PHP 初学者帮助)如果您打算使用 SMTP,请在此行之后添加您的 SMTP 代码

Posted

技术标签:

【中文标题】(PHP 初学者帮助)如果您打算使用 SMTP,请在此行之后添加您的 SMTP 代码【英文标题】:(PHP Beginner Help) If you intend you use SMTP, add your SMTP Code after this Line 【发布时间】:2021-10-01 23:03:18 【问题描述】:

我是 phphtml 新手,在使用 PHP 发送电子邮件方面需要帮助。我使用的代码是一个带有良好文档代码的 web 模板,这可能是一个简单的修复。

问题:当我在 Live Server 中为联系表单发送测试电子邮件并按“发送”时,没有任何反应,没有电子邮件通过,也没有成功消息。我是否在我的 PHP 代码中遗漏了某些内容,还是需要设置 SMTP?

*我的知识很基础,所以这个问题可能会被问错。感谢您的任何反馈!

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';

// If you intend you use SMTP, uncomment next line
require 'phpmailer/src/SMTP.php';


// Set the recipient email address here
$recipients = array();

$recipients[] = array(
    'email' => 'contact@westonborst.com',
    'name' => 'Weston'
);


// Set the sender email address here
$sender = array(
    'email' => 'contact@westonborst.com',
    'name' => 'Weston'
);


// reCaptcha Secret Key - Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = '';


// PHPMailer Initialization
$mail = new PHPMailer();

// If you intend you use SMTP, add your SMTP Code after this Line


// End of SMTP


// Form Messages
$message = array(
    'success'           => 'Thank you for your message. It has been sent.',
    'error'             => 'There was an error trying to send your message. Please try again later.',
    'error_bot'         => 'Bot Detected! Message could not be send. Please try again.',
    'error_unexpected'  => 'There was an unexpected error trying to send your message. Please try again later.',
    'recaptcha_invalid' => 'Captcha not Validated! Please Try Again.',
    'recaptcha_error'   => 'Captcha not Submitted! Please Try Again.'
);

// Form Processor
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) 

    $prefix    = !empty( $_POST['prefix'] ) ? $_POST['prefix'] : '';
    $submits   = $_POST;
    $botpassed = false;
    
    $message_form                 = !empty( $submits['message'] ) ? $submits['message'] : array();
    $message['success']           = !empty( $message_form['success'] ) ? $message_form['success'] : $message['success'];
    $message['error']             = !empty( $message_form['error'] ) ? $message_form['error'] : $message['error'];
    $message['error_bot']         = !empty( $message_form['error_bot'] ) ? $message_form['error_bot'] : $message['error_bot'];
    $message['error_unexpected']  = !empty( $message_form['error_unexpected'] ) ? $message_form['error_unexpected'] : $message['error_unexpected'];
    $message['recaptcha_invalid'] = !empty( $message_form['recaptcha_invalid'] ) ? $message_form['recaptcha_invalid'] : $message['recaptcha_invalid'];
    $message['recaptcha_error']   = !empty( $message_form['recaptcha_error'] ) ? $message_form['recaptcha_error'] : $message['recaptcha_error'];


    // Bot Protection
    if( isset( $submits[ $prefix . 'botcheck' ] ) ) 
        $botpassed = true;
    

    if( !empty( $submits[ $prefix . 'botcheck' ] ) ) 
        $botpassed = false;
    

    if( $botpassed == false ) 
        echo ' "alert": "error", "message": "' . $message['error_bot'] . '" ';
        exit;
    


    // reCaptcha
    if( isset( $submits['g-recaptcha-response'] ) ) 

        $recaptcha_data = array(
            'secret' => $recaptcha_secret,
            'response' => $submits['g-recaptcha-response']
        );

        $rc_verify = curl_init();
        curl_setopt( $rc_verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify" );
        curl_setopt( $rc_verify, CURLOPT_POST, true );
        curl_setopt( $rc_verify, CURLOPT_POSTFIELDS, http_build_query( $recaptcha_data ) );
        curl_setopt( $rc_verify, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $rc_verify, CURLOPT_RETURNTRANSFER, true );
        $rc_response = curl_exec( $rc_verify );

        $g_response = json_decode( $rc_response );

        if ( $g_response->success !== true ) 
            echo ' "alert": "error", "message": "' . $message['recaptcha_invalid'] . '" ';
            exit;
        
    

    $html_title = !empty( $submits['html_title'] ) ? $submits['html_title'] : 'Form Response';
    $forcerecaptcha = ( !empty( $submits['force_recaptcha'] ) && $submits['force_recaptcha'] != 'false' ) ? true : false;
    $replyto = !empty( $submits['replyto'] ) ? explode( ',', $submits['replyto'] ) : false;

    if( $forcerecaptcha ) 
        if( !isset( $submits['g-recaptcha-response'] ) ) 
            echo ' "alert": "error", "message": "' . $message['recaptcha_error'] . '" ';
            exit;
        
    

    $mail->Subject = !empty( $submits['subject'] ) ? $submits['subject'] : 'Form response from your website';
    $mail->SetFrom( $sender['email'] , $sender['name'] );

    if( !empty( $replyto ) ) 
        if( count( $replyto ) > 1 ) 
            $replyto_e = $submits[ $replyto[0] ];
            $replyto_n = $submits[ $replyto[1] ];
            $mail->AddReplyTo( $replyto_e , $replyto_n );
         elseif( count( $replyto ) == 1 ) 
            $replyto_e = $submits[ $replyto[0] ];
            $mail->AddReplyTo( $replyto_e );
        
    

    foreach( $recipients as $recipient ) 
        $mail->AddAddress( $recipient['email'] , $recipient['name'] );
    

    $unsets = array( 'prefix', 'subject', 'replyto', 'message', $prefix . 'botcheck', 'g-recaptcha-response', 'force_recaptcha', $prefix . 'submit' );

    foreach( $unsets as $unset ) 
        unset( $submits[ $unset ] );
    

    $fields = array();

    foreach( $submits as $name => $value ) 
        if( empty( $value ) ) continue;

        $name = str_replace( $prefix , '', $name );
        $name = ucwords( str_replace( '-', ' ', $name ) );

        if( is_array( $value ) ) 
            $value = implode( ', ', $value );
        

        $fields[$name] = $value;
    

    $response = array();

    foreach( $fields as $fieldname => $fieldvalue ) 
        $response[] = $fieldname . ': ' . $fieldvalue;
    

    $referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';

    $body = implode( "<br>", $response ) . $referrer;

    $mail->MsgHTML( $body );
    $sendEmail = $mail->Send();

    if( $sendEmail == true ):
        if( $autores && !empty( $replyto_e ) ) 
            $send_arEmail = $autoresponder->Send();
        

        echo ' "alert": "success", "message": "' . $message['success'] . '" ';
    else:
        echo ' "alert": "error", "message": "' . $message['error'] . '<br><br><strong>Reason:</strong><br>' . $mail->ErrorInfo . '" ';
    endif;

 else 
    echo ' "alert": "error", "message": "' . $message['error_unexpected'] . '" ';


?>

【问题讨论】:

欢迎来到 Stack Overflow。当您编写代码时遇到问题时,最好将其剥离到复制问题所需的最低限度(实际上最好以功能增量来构建代码,并在进行过程中测试每个新事物)。如果您遇到困难,那么只需发布重新创建问题所需的代码(有关于此问题的常见问题解答) 【参考方案1】:

不知道为什么它不会发送,这是我试过的?有什么建议吗? (我从代码中删除了我的密码)

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';

// If you intend you use SMTP, uncomment next line
require 'phpmailer/src/SMTP.php';


// Set the recipient email address here
$recipients = array();

$recipients[] = array(
    'email' => 'borstweston@gmail.com',
    'name' => 'Weston'
);


// Set the sender email address here
$sender = array(
    'email' => 'borstweston@gmail.com',
    'name' => 'Weston'
);


// reCaptcha Secret Key - Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = '';


// PHPMailer Initialization
$mail = new PHPMailer();

// If you intend you use SMTP, add your SMTP Code after this Line
$mail->IsSMTP(); // enable SMTP
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com.";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "borstweston@gmail.com";
$mail->Password = "";
$mail->SetFrom("borstweston@gmail.com");
$mail->Subject = "";
$mail->Body ="";
$mail->AddAddress($sendTo);



// End of SMTP


// Form Messages
$message = array(
    'success'           => 'Thank you for your message. It has been sent.',
    'error'             => 'There was an error trying to send your message. Please try again later.',
    'error_bot'         => 'Bot Detected! Message could not be send. Please try again.',
    'error_unexpected'  => 'There was an unexpected error trying to send your message. Please try again later.',
    'recaptcha_invalid' => 'Captcha not Validated! Please Try Again.',
    'recaptcha_error'   => 'Captcha not Submitted! Please Try Again.'
);

// Form Processor
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) 

    $prefix    = !empty( $_POST['prefix'] ) ? $_POST['prefix'] : '';
    $submits   = $_POST;
    $botpassed = false;
    
    $message_form                 = !empty( $submits['message'] ) ? $submits['message'] : array();
    $message['success']           = !empty( $message_form['success'] ) ? $message_form['success'] : $message['success'];
    $message['error']             = !empty( $message_form['error'] ) ? $message_form['error'] : $message['error'];
    $message['error_bot']         = !empty( $message_form['error_bot'] ) ? $message_form['error_bot'] : $message['error_bot'];
    $message['error_unexpected']  = !empty( $message_form['error_unexpected'] ) ? $message_form['error_unexpected'] : $message['error_unexpected'];
    $message['recaptcha_invalid'] = !empty( $message_form['recaptcha_invalid'] ) ? $message_form['recaptcha_invalid'] : $message['recaptcha_invalid'];
    $message['recaptcha_error']   = !empty( $message_form['recaptcha_error'] ) ? $message_form['recaptcha_error'] : $message['recaptcha_error'];


    // Bot Protection
    if( isset( $submits[ $prefix . 'botcheck' ] ) ) 
        $botpassed = true;
    

    if( !empty( $submits[ $prefix . 'botcheck' ] ) ) 
        $botpassed = false;
    

    if( $botpassed == false ) 
        echo ' "alert": "error", "message": "' . $message['error_bot'] . '" ';
        exit;
    


    // reCaptcha
    if( isset( $submits['g-recaptcha-response'] ) ) 

        $recaptcha_data = array(
            'secret' => $recaptcha_secret,
            'response' => $submits['g-recaptcha-response']
        );

        $rc_verify = curl_init();
        curl_setopt( $rc_verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify" );
        curl_setopt( $rc_verify, CURLOPT_POST, true );
        curl_setopt( $rc_verify, CURLOPT_POSTFIELDS, http_build_query( $recaptcha_data ) );
        curl_setopt( $rc_verify, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $rc_verify, CURLOPT_RETURNTRANSFER, true );
        $rc_response = curl_exec( $rc_verify );

        $g_response = json_decode( $rc_response );

        if ( $g_response->success !== true ) 
            echo ' "alert": "error", "message": "' . $message['recaptcha_invalid'] . '" ';
            exit;
        
    

    $html_title = !empty( $submits['html_title'] ) ? $submits['html_title'] : 'Form Response';
    $forcerecaptcha = ( !empty( $submits['force_recaptcha'] ) && $submits['force_recaptcha'] != 'false' ) ? true : false;
    $replyto = !empty( $submits['replyto'] ) ? explode( ',', $submits['replyto'] ) : false;

    if( $forcerecaptcha ) 
        if( !isset( $submits['g-recaptcha-response'] ) ) 
            echo ' "alert": "error", "message": "' . $message['recaptcha_error'] . '" ';
            exit;
        
    

    $mail->Subject = !empty( $submits['subject'] ) ? $submits['subject'] : 'Form response from your website';
    $mail->SetFrom( $sender['email'] , $sender['name'] );

    if( !empty( $replyto ) ) 
        if( count( $replyto ) > 1 ) 
            $replyto_e = $submits[ $replyto[0] ];
            $replyto_n = $submits[ $replyto[1] ];
            $mail->AddReplyTo( $replyto_e , $replyto_n );
         elseif( count( $replyto ) == 1 ) 
            $replyto_e = $submits[ $replyto[0] ];
            $mail->AddReplyTo( $replyto_e );
        
    

    foreach( $recipients as $recipient ) 
        $mail->AddAddress( $recipient['email'] , $recipient['name'] );
    

    $unsets = array( 'prefix', 'subject', 'replyto', 'message', $prefix . 'botcheck', 'g-recaptcha-response', 'force_recaptcha', $prefix . 'submit' );

    foreach( $unsets as $unset ) 
        unset( $submits[ $unset ] );
    

    $fields = array();

    foreach( $submits as $name => $value ) 
        if( empty( $value ) ) continue;

        $name = str_replace( $prefix , '', $name );
        $name = ucwords( str_replace( '-', ' ', $name ) );

        if( is_array( $value ) ) 
            $value = implode( ', ', $value );
        

        $fields[$name] = $value;
    

    $response = array();

    foreach( $fields as $fieldname => $fieldvalue ) 
        $response[] = $fieldname . ': ' . $fieldvalue;
    

    $referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';

    $body = implode( "<br>", $response ) . $referrer;

    $mail->MsgHTML( $body );
    $sendEmail = $mail->Send();

    if( $sendEmail == true ):
        if( $autores && !empty( $replyto_e ) ) 
            $send_arEmail = $autoresponder->Send();
        

        echo ' "alert": "success", "message": "' . $message['success'] . '" ';
    else:
        echo ' "alert": "error", "message": "' . $message['error'] . '<br><br><strong>Reason:</strong><br>' . $mail->ErrorInfo . '" ';
    endif;

 else 
    echo ' "alert": "error", "message": "' . $message['error_unexpected'] . '" ';


?>

【讨论】:

【参考方案2】:

如果您正确填写所有内容,则应该可以。 (我试过了)

require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();


try 
    $mail->IsSMTP(); // enable SMTP
    $mail->CharSet = 'UTF-8';
    $mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true; // authentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 465; // or 587
    $mail->IsHTML(true);
    $mail->Username = "Your Email Address";
    $mail->Password = "Your Password";
    $mail->SetFrom("From Name");
    $mail->Subject = "Message Subject";
    $mail->Body ="Message Body ";
    $mail->AddAddress('Sent email to this address');

    if($mail->Send()) 
        // e-posta başarılı ile gönderildi
      echo 'success';
     else 
        echo 'error';
    
 catch (Exception $e) 
    echo 'error : '.$e;

如果不是,请分享您收到的错误消息。

【讨论】:

你把 $mail 放在哪里 -> Host = "smt.yandex.com",我用 gmail 帐户替换它吗?对于用户名和密码,我是否输入我的 gmail 登录信息?感谢您的帮助! 是的,您需要输入您的 gmail 用户名和密码,并将主机更改为“smtp.gmail.com”。 我在下面粘贴了我尝试过的代码,有什么遗漏吗?感谢您的帮助!

以上是关于(PHP 初学者帮助)如果您打算使用 SMTP,请在此行之后添加您的 SMTP 代码的主要内容,如果未能解决你的问题,请参考以下文章

对象作为 React 子级无效。如果您打算渲染一组孩子,请改用数组 - FlatList

PHP 如果你不存在,我们会帮助你。那我们打算打开你。

React 错误:对象作为 React 子级无效,如果您打算渲染子级集合,请改用数组

对象作为反应组件无效。 (找到:带有键 的对象)。如果您打算渲染一组孩子,请改用数组

如何将 php 连接到 google SMTP 并发送邮件? [复制]

错误:对象作为 React 子项无效(找到:带有键 的对象)。如果您打算渲染一组孩子,请改用数组