dtnpzghys01643322 2018-06-06 16:22
浏览 47

使用gmail api php发送邮件

I have been searching for Google documentation to send a mail using gmail oauth 2 credentials. I just created a new project in console.developers.google and enabled gmail using gmail api. I created oauth credentials and even configured them in consent screen. But I am unable to send the mail I just get the following response whenever I run my php file on the server.

An error occurred: {
"error": {
"errors": [
{
 "domain": "global",
 "reason": "insufficientPermissions",
 "message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}

I tried executing the following code

<?php
require __DIR__ . '/vendor/autoload.php';
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Send mail');
$client->setSubject('Verification mail');
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
$client->setAuthConfig('client_secret.json');
$client->setAccessType(["https://www.googleapis.com/auth/gmail.compose"]);
$credentialsPath = expandHomeDirectory('credentials.json');
if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:
%s
", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
    if (!file_exists(dirname($credentialsPath))) {
        mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s
", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath,     json_encode($client->getAccessToken()));
}
return $client;
}
function expandHomeDirectory($path)
{
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
$client = getClient();
$service = new Google_Service_Gmail($client);
try {
    $strSubject = "Verificaion mail";
    $strRawMessage = "From: Me<rammanojpotla1608@gmail.com>
";
    $strRawMessage .= "To: manoj<rammanoj.potla@gmail.com>
";
    $strRawMessage .= "CC: rammanoj<rammanojpotla1608@gmail.com>
";
    $strRawMessage .= "Subject: =?utf-8?B?" . base64_encode($strSubject) .     "?=
";
    $strRawMessage .= "MIME-Version: 1.0
";
    $strRawMessage .= "Content-Type: text/html; charset=utf-8
";
    $strRawMessage .= "Content-Transfer-Encoding: base64" . "

";
    $strRawMessage .= "A simple verification mail!" . "
";
    $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
    $msg = new Google_Service_Gmail_Message();
    $msg->setRaw($mime);
    $service->users_messages->send("me", $msg);
} catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
}
?>

can anyone provide a better explanation of above code along with the reason for the error. Thanks!

  • 写回答

2条回答 默认 最新

  • dongzichan2886 2018-06-07 08:26
    关注

    I guess the error is due to the access type when I changed the access type it gave me an another error. I guess it is raising an error saying that there are not permissions to access your account. This might be due to giving a wrong access token in crdentials.json file or may be because of expiry of access token. However minimizing the above code. I tried understanding and wrote a simple one.

    <?php
    require __DIR__ . '/vendor/autoload.php';
     $client = new Google_Client();
     $client->setScopes(Google_Service_Gmail::GMAIL_COMPOSE  );
     $client->setAuthConfig('client_secret.json');
     $credentialsPath = __DIR__.'/credentials.json';
     if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
     } else {
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:
    %s
    ", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        printf("Credentials saved to %s
    ", $credentialsPath);
     }
     $client->setAccessToken($accessToken);
     if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath,   json_encode($client->getAccessToken()));
    }
    $service = new Google_Service_Gmail($client);
    try {
        $strSubject = "Verificaion mail";
        $strRawMessage = "From: Me<rammanojpotla1608@gmail.com>
    ";
        $strRawMessage .= "To: manoj<rammanoj.potla@gmail.com>
    ";
        $strRawMessage .= "CC: rammanoj<rammanojpotla1608@gmail.com>
    ";
        $strRawMessage .= "Subject: =?utf-8?B?" . base64_encode($strSubject) .     "?=
    ";
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
        $service->users_messages->send("me", $msg);
        echo "mail sent";
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
    
    ?>
    

    Google_client creates a new google client. Setscopes are need to define the type of operations you are going to perform with the access specified or given to you. Initially, it checks if file named credentials.json is there or not. If it is there it accesses the access_token of the user and perform the desired operation. Here my operation is to send mail using gmail api. So, I created a new Google_Service_Gmail class to perform it. If there is no credentials.json file then it accesses the client_secret.json file that contain the client_id and client_secrent. Using both of them you can generate your access token.

    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装