SQLの窓

2015年01月13日


GitHub の google-api-php-client( PHP ) を使って、Gmail でメールを送る

google-api-php-client
Client ID と Client secret と Redirect URIs が必要です ( APIs Console )



Users.messages: send

google-api-php-client は Google のあらゆる API にアクセスする為に数多くのクラスが用意されており、かつ標準化されています。examples フォルダの内容は、Google ドライブで作成されていますが、よくよく各クラスの内容を読んで、Google の英文ドキュメントを参考にしながら世の中の記事を参考にすればなんとかなりそうなものです。

今回、Gmail を使ってのメール送信は以下の英文記事を参考にしました。

Using Gmail API to Send Rich Text Emails

このコードは、利用するには不完全ですが、クラスと Google のドキュメントを読み解く資料としては十分の内容でした。

また、ここで使われる Base64URL というエンコードは、なかなか興味深い内容ですが、そもそもメールはそういう仕様の集合体なので、基本知識が無い場合はそのままただ使うといいと思います。( ここが最も参考になりました )

send メソッドが所属するのは、Google_Service_Gmail_UsersMessages_Resource というクラスで、Google_Service_Gmail のコンストラクタでプロパティとして設定されるものです。よって、実行が $service->users_messages->send("me", $msg); という形になるわけです。
<?php
/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
include_once "templates/base.php";
session_start();

header( "Content-Type: text/html; Charset=utf-8" );
header( "pragma: no-cache" );
header( "Expires: Wed, 31 May 2000 14:59:58 GMT" );
header( "Cache-control: no-cache" );

require_once realpath(dirname(__FILE__) . '/../autoload.php');

/************************************************
  $redirect_uri はこのスクリプトの URL
 ************************************************/
$client_id = '';
$client_secret = '';
$redirect_uri = 'http://localhost/gapi/examples/gmail-send.php';

/************************************************
  クライアントの作成
 ************************************************/
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);

/************************************************
  サービスの作成
 ************************************************/
// https://developers.google.com/gmail/api/auth/scopes
// https://developers.google.com/gmail/api/v1/reference/users/messages/send
$client->addScope("https://mail.google.com/");
$service = new Google_Service_Gmail($client);

/************************************************
  アクセストークンの取得プロセス
 ************************************************/
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  if ($client->isAccessTokenExpired()) {
    unset($_SESSION['access_token']);
  }
} else {
  $authUrl = $client->createAuthUrl();
}

/************************************************
  アクセストークンが取得できた時の処理
 ************************************************/
if ($client->getAccessToken() && $_POST['send'] != '' && $_POST['body'] != '') {

  // メール送信
  $subject = mb_convert_encoding( $_POST['subject'], "JIS", "UTF-8" );
  $subject = "Subject: =?ISO-2022-JP?B?" . base64_encode($subject) . "?=";
  $to = "To: {$_POST['to']}";
  $body = $_POST['body'];

  $send_data = "$subject¥n$to¥n¥n$body";
  // Base64URL
  $send_data = rtrim(strtr(base64_encode($send_data), '+/', '-_'), '=');
  $msg = new Google_Service_Gmail_Message();
  $msg->setRaw($send_data);
  $result = $service->users_messages->send("me", $msg);

}

echo pageHeader("Gmail メール送信");
if ($client->getAccessToken()) {
?>
<div style='width:300px;margin:auto'>
<form method="post" >
<input type="text" name="to"><br>
<input type="text" name="subject"><br>
<textarea name="body" style='height:100px;'></textarea><br>
<input type="submit" name="send" value="送信">
</form>
</div>
<?php
}
?>
<div class="box">
  <div class="request">
<?php 
if (isset($authUrl)) {
  echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
}
?>
  </div>

  <pre class="shortened" style='width:100%;height:500px;'>
<?php 
if (isset($result) && $result) {
  print_r($result);
}
?>
  </pre>
</div>

スコープとして、https://mail.google.com/ を使用していますが、これは最も権限の大きいスコープで、メール送信はこれを使う必要は必ずしも無いはずです。

関連する記事


タグ:gmail google API
【Googleの最新記事】
posted by lightbox at 2015-01-13 00:08 | Google | このブログの読者になる | 更新情報をチェックする
container 終わり



フリーフォントで簡単ロゴ作成
フリーフォントでボタン素材作成
フリーフォントで吹き出し画像作成
フリーフォントではんこ画像作成
ほぼ自由に利用できるフリーフォント
フリーフォントの書体見本とサンプル
画像を大きく見る為のウインドウを開くボタンの作成

CSS ドロップシャドウの参考デモ
イラストAC
ぱくたそ
写真素材 足成
フリーフォント一覧
utf8 文字ツール
右サイド 終わり
base 終わり