OAuth 2.0 配置设置
P粉373596828
P粉373596828 2024-04-06 11:12:57
[PHP讨论组]

我使用 phpmailer 通过 smtp.google.com 服务器发送邮件,但现在它无法正常工作,因为他们说使用 OAuth2.0 配置。

我参考了一些示例并使用使用 PhpMailer 和 Gmail XOAUTH2 发送电子邮件创建了一个示例页面来测试它,但它不起作用。谁能指出代码中出了什么问题吗?

这是我的 html 页面

sendContactMail($_POST);
}
?>


Contact Us Form



    




Message'>

这是 get_oauth_token.php


 * @author Jim Jagielski (jimjag) 
 * @author Andy Prevost (codeworxtech) 
 * @author Brent R. Matzelle (original founder)
 * @copyright 2012 - 2020 Marcus Bointon
 * @copyright 2010 - 2012 Jim Jagielski
 * @copyright 2004 - 2009 Andy Prevost
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 * @note This program is distributed in the hope that it will be useful - WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 */

/**
 * Get an OAuth2 token from an OAuth2 provider.
 * * Install this script on your server so that it's accessible
 * as [https/http]:////get_oauth_token.php
 * e.g.: http://localhost/phpmailer/get_oauth_token.php
 * * Ensure dependencies are installed with 'composer install'
 * * Set up an app in your Google/Yahoo/Microsoft account
 * * Set the script address as the app's redirect URL
 * If no refresh token is obtained when running this file,
 * revoke access to your app and run the script again.
 */

namespace PHPMailer\PHPMailer;

/**
 * Aliases for League Provider Classes
 * Make sure you have added these to your composer.json and run `composer install`
 * Plenty to choose from here:
 * @see http://oauth2-client.thephpleague.com/providers/thirdparty/
 */
//@see https://github.com/thephpleague/oauth2-google
use League\OAuth2\Client\Provider\Google;
//@see https://packagist.org/packages/hayageek/oauth2-yahoo
use Hayageek\OAuth2\Client\Provider\Yahoo;
//@see https://github.com/stevenmaguire/oauth2-microsoft
use Stevenmaguire\OAuth2\Client\Provider\Microsoft;

if (!isset($_GET['code']) && !isset($_GET['provider'])) {
    ?>

Select Provider:
Google
Yahoo
Microsoft/Outlook/Hotmail/Live/Office365
$clientId, 'clientSecret' => $clientSecret, 'redirectUri' => $redirectUri, 'accessType' => 'offline' ]; $options = []; $provider = null; switch ($providerName) { case 'Google': $provider = new Google($params); $options = [ 'scope' => [ 'https://mail.google.com/' ] ]; break; case 'Yahoo': $provider = new Yahoo($params); break; case 'Microsoft': $provider = new Microsoft($params); $options = [ 'scope' => [ 'wl.imap', 'wl.offline_access' ] ]; break; } if (null === $provider) { exit('Provider missing'); } if (!isset($_GET['code'])) { //If we don't have an authorization code then get one $authUrl = $provider->getAuthorizationUrl($options); $_SESSION['oauth2state'] = $provider->getState(); header('Location: ' . $authUrl); exit; //Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); unset($_SESSION['provider']); exit('Invalid state'); } else { unset($_SESSION['provider']); //Try to get an access token (using the authorization code grant) $token = $provider->getAccessToken( 'authorization_code', [ 'code' => $_GET['code'] ] ); //Use this to interact with an API on the users behalf //Use this to get a new access token if the old one expires echo 'Refresh Token: ', $token->getRefreshToken(); }

提交表单时,显示错误

致命错误:未捕获错误:在 lib/MailService.php:31 中找不到类“Phppot\SMTP”堆栈跟踪:#0 index.php(7): Phppot\MailService->sendContactMail(Array) #1 {main}抛出在 lib/MailService.php 第 31 行

已编辑

这是我的 MailService.php 文件

Port to send
        // mail using phpmail instead of smtp.
        $mail->isSMTP();
        //Enable SMTP debugging
        //SMTP::DEBUG_OFF = off (for production use)
        //SMTP::DEBUG_CLIENT = client messages
        //SMTP::DEBUG_SERVER = client and server messages
        $mail->SMTPDebug = SMTP::DEBUG_OFF;

        //Set the hostname of the mail server
        $mail->Host = Config::SMTP_HOST;

        //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
        $mail->Port = Config::SMTP_PORT;

        //Set the encryption mechanism to use - STARTTLS or SMTPS
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

        //Whether to use SMTP authentication
        $mail->SMTPAuth = true;

        //Set AuthType to use XOAUTH2
        $mail->AuthType = 'XOAUTH2';

        //Fill in authentication details here
        //Either the gmail account owner, or the user that gave consent
        $oauthUserEmail = Config::OAUTH_USER_EMAIL;
        $clientId = Config::OAUTH_CLIENT_ID;
        $clientSecret = Config::OAUTH_SECRET_KEY;

        //Obtained by configuring and running get_oauth_token.php
        //after setting up an app in Google Developer Console.
        $refreshToken = Config::REFRESH_TOKEN;

        //Create a new OAuth2 provider instance
        $provider = new Google(
            [
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
            ]
            );

        //Pass the OAuth provider instance to PHPMailer
        $mail->setOAuth(
            new OAuth(
                [
                    'provider' => $provider,
                    'clientId' => $clientId,
                    'clientSecret' => $clientSecret,
                    'refreshToken' => $refreshToken,
                    'userName' => $oauthUserEmail,
                ]
                )
            );

        // Recipients
        $mail->setFrom(Config::SENDER_EMAIL, $name);
        $mail->addReplyTo($email, $name);

        $mail->addAddress(Config::RECIPIENT_EMAIL, Config::RECIPIENT_EMAIL);

        $mail->Subject = $subject;

        $mail->CharSet = PHPMailer::CHARSET_UTF8;
        $mail->msgHTML($mailBody);

        //Replace the plain text body with one created manually
        $mail->AltBody = 'This is a plain-text message body';

        if (!$mail->send()) {
            $output = json_encode(array('type'=>'error', 'text' => ''.$from.' is invalid.'));
            $output = json_encode(array('type'=>'error', 'text' => 'Server error. Please mail vincy@phppot.com'));
        } else {
            $output = json_encode(array('type'=>'message', 'text' => 'Thank you, I will get back to you shortly.'));
        }
        return $output;
    }
}

P粉373596828
P粉373596828

全部回复(1)
P粉107991030

您遇到命名空间问题。你正在这样做:

namespace Phppot;

use Phppot\Config;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

然后使用这个:

$mail->SMTPDebug = SMTP::DEBUG_OFF;

因为您尚未将 PHPMailer 包中的 SMTP 类名导入到您的命名空间中,所以它将查找名为 Phppot\SMTP 的类,该类不存在,因此会出现错误消息。您可以通过添加以下内容来解决此问题:

use PHPMailer\PHPMailer\SMTP;

这将使它使用 PHPMailer 中正确的 SMTP 类。

请注意,这里可能存在另一个问题。您已经 use Phppot\Config;,但您已经在 Phppot 命名空间中,因此将查找名为 Phppot\Phppot\Config,可能不存在。如果该类已位于您声明的命名空间中,则不需要为其使用 use 语句。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号