代码之家  ›  专栏  ›  技术社区  ›  Logos

使用PHP中的GMail API发送电子邮件

  •  1
  • Logos  · 技术社区  · 7 年前

    我应该把一个旧项目的邮件服务换成GMail。然而,该项目使用的是PHP,而PHP代码的文档在google文档页面中尚不可用。我想用一个简单的邮件正文来测试发送电子邮件,下面是代码:

    require_once __DIR__."/google-api-php-client-2.2.1/vendor/autoload.php";
    
    define("APPLICATION_NAME", "Gmail API PHP Quickstart");
    define("CREDENTIALS_PATH", "~/.credentials/gmail-php-quickstart.json");
    define("CLIENT_SECRET_PATH", __DIR__."/client_secret.json");
    
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/gmail-php-quickstart.json
    define('SCOPES', implode(' ', array(
        Google_Service_Gmail::GMAIL_READONLY)
    ));
    
    date_default_timezone_set('America/New_York'); // Prevent DateTime tz exception
    /*
    if (php_sapi_name() != 'cli') {
        throw new Exception('This application must be run on the command line.');
    }
    */
    
    /**
    * Returns an authorized API client.
    * @return Google_Client the authorized client object
    */
    function getClient() {
        $client = new Google_Client();
        $client->setApplicationName(APPLICATION_NAME);
        $client->setScopes(SCOPES);
        $client->setAuthConfig(CLIENT_SECRET_PATH);
        $client->setAccessType('offline');
    
        // Load previously authorized credentials from a file.
        $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
        if (file_exists($credentialsPath)) {
            $accessToken = json_decode(file_get_contents($credentialsPath), true);
        }
        else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));
    
            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
    
            // Store the credentials to disk.
            if(!file_exists(dirname($credentialsPath))) {
                mkdir(dirname($credentialsPath), 0700, true);
            }
            file_put_contents($credentialsPath, json_encode($accessToken));
            printf("Credentials saved to %s\n", $credentialsPath);
        }
        $client->setAccessToken($accessToken);
    
        // Refresh the token if it's expired.
        if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }
    
    /**
    * Expands the home directory alias '~' to the full path.
    * @param string $path the path to expand.
    * @return string the expanded path.
    */
    function expandHomeDirectory($path) {
        $homeDirectory = getenv('HOME');
        if (empty($homeDirectory)) {
            $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
        }
        return str_replace('~', realpath($homeDirectory), $path);
    }
    
    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Gmail($client);
    
    // Print the labels in the user's account.
    $user = 'me';
    $message = new Google_Service_Gmail_Message();
    $messagePart = new Google_Service_Gmail_MessagePart();
    $messagePartBody = new Google_Service_Gmail_MessagePartBody();
    $messagePartHeader = new Google_Service_Gmail_MessagePartHeader();
    
    $messagePartBody->setData("TEST BY FAROUK");
    
    $messagePart->setHeader($messagePartHeader);
    $messagePart->setBody($messagePartBody);
    $message->setPayLoad($messagePart);
    
    $service->users_messages->send($user, $message, null);
    

    问题在于这一部分,尚未完成:

    $user = 'me';
    $message = new Google_Service_Gmail_Message();
    $messagePart = new Google_Service_Gmail_MessagePart();
    $messagePartBody = new Google_Service_Gmail_MessagePartBody();
    $messagePartHeader = new Google_Service_Gmail_MessagePartHeader();
    
    $messagePartBody->setData("TEST BY ME");
    
    $messagePart->setHeader($messagePartHeader);
    $messagePart->setBody($messagePartBody);
    $message->setPayLoad($messagePart);
    
    $service->users_messages->send($user, $message, null);
    

    我知道我必须创建这些类的对象,但我不知道应该使用它们的setter在参数中设置什么样的数据。

    请给出一个简单的代码来发送“你好,世界!”发送到电子邮件地址,如foo@gmail.com.谢谢

    1 回复  |  直到 7 年前
        1
  •  5
  •   trueChazza    7 年前

    此工作示例使用服务帐户,请根据您的需要进行调整:

        $user_to_impersonate = "email_to_impersonate@yourdomain.com";
        putenv("GOOGLE_APPLICATION_CREDENTIALS=google-api-php-client/service-account-credentials.json");
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->setSubject($user_to_impersonate);
        $client->setApplicationName("My Mailer");
        $client->setScopes(["https://www.googleapis.com/auth/gmail.compose"]);
        $service = new Google_Service_Gmail($client);
        // Process data
        try {
            $strSubject = "Set the email subject here";
            $strRawMessage = "From: Me<myemail@mydomain.com>\r\n";
            $strRawMessage .= "To: Foo<foo@gmail.com>\r\n";
            $strRawMessage .= "CC: Bar<bar@gmail.com>\r\n";
            $strRawMessage .= "Subject: =?utf-8?B?" . base64_encode($strSubject) . "?=\r\n";
            $strRawMessage .= "MIME-Version: 1.0\r\n";
            $strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
            $strRawMessage .= "Content-Transfer-Encoding: base64" . "\r\n\r\n";
            $strRawMessage .= "Hello World!" . "\r\n";
            // The message needs to be encoded in Base64URL
            $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
            $msg = new Google_Service_Gmail_Message();
            $msg->setRaw($mime);
            //The special value **me** can be used to indicate the authenticated user.
            $service->users_messages->send("me", $msg);
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    

    希望这能帮助你开始

    编辑

    进一步帮助 https://stackoverflow.com/a/37256138/9482295