Gmail 連携 - kintone から Gmail の送受信をしよう!

目次

caution
警告

2020 年 8 月改訂のセキュアコーディング ガイドライン に抵触する内容が含まれています。認証情報が漏洩した場合の影響を考慮して慎重に検討してください。
該当箇所:アクセストークン保存部分。

information

kintone にメールを取り込みたい場合は、 サイボウズ オフィシャル SI パートナー クロス・ヘッド株式会社による有償のプラグイン (External link) もご検討ください。

はじめに

Gmail が kintone 上で送受信できるサンプルです。

メールを kintone に取り込むことで、他の kintone アプリとの連携がしやすくなります。

概要

連携の流れは以下となっています。

  1. kintone から Google のクライアント ID をもとに OAuth 認証
  2. kintone から Google のアクセストークン取得
  3. アクセストークンを利用して Google API を実行
  4. レスポンスを kintone のアプリに登録

kintone アプリの作成

kintone アプリでは以下のフィールドを配置してください。

フィールド名 フィールドタイプ フィールドコード
Date and time 日時 Date_and_time
subject 文字列(1行) subject
contents リッチエディター message
FROM 文字列(1行) from
TO 文字列(1行) to
CC 文字列(1行) cc
BCC 文字列(1行) bcc
messageId 文字列(1行) message_id
mailAccount 文字列(1行) email_account
attachFile 添付ファイル attachment
owner ユーザー選択 owner
labels 文字列(1行) labels_id
threadID 文字列(1行) thread_id

こちらがアプリの配置したフィールドのフォーム画面です。

Google API の認証情報の設定

1. プロジェクトの作成

Google API を利用するために Google API の認証情報を設定します。
まず、 Google APIのデベロッパーコンソール (External link) にログインします。
画面が表示されたら、「プロジェクトを選択」をクリックします。
すでに作成したプロジェクトがある場合は、前回設定したプロジェクト名が表示されています。

右上の「新しいプロジェクト」をクリックして、新規プロジェクトを作成します。

プロジェクト名を入力し、「作成」ボタンをクリックすると、新規プロジェクトが作成されます。
ここではプロジェクト名を「kintone-Gmail」にします。

2. Gmail API の有効化

「API の概要に移動」をクリックします。

次に左サイドメニューより、「有効な API とサービス」を選択し、「✙ API とサービスの有効化」を選択します。

「Gmail API」で検索し、検索結果から Gmail API を選択します。

「有効にする」をクリックして、Gmail API を有効にします。

3. 認証情報の作成

「認証情報を作成」をクリックします。

使用する API に「Gmail API」を選択し、アクセスするデータの種類に「ユーザーデータ」を選択し、「次へ」をクリックします。

「User Type」を指定し、「作成」ボタンをクリックします。
今回は検証用として「外部」を選択します。利用状況に応じて適切に選択してください。

アプリケーション名を入力します。ここでは「kintone-Gmail」にします。
ユーザーサポートメールをログインユーザーのメールアドレスにし、デベロッパーの連絡先情報を入力して「保存して次へ」ボタンをクリックします。
他の項目は利用状況に応じて適切に設定してください。

「スコープ」と「テストユーザー」画面で必要な情報を入力して「保存して次へ」をクリックします。
今回は検証用として何も入力せずに「保存して次へ」クリックします。利用状況に応じて適切に設定してください。

4. クライアント ID の作成

「アプリケーションの種類」に「Web アプリケーション」を指定し、名前を自由に入力、「承認済みの JavaScript 生成元」にお使いの kintone の URL を入力し、「作成」ボタンをクリックしてクライアント ID を生成します。

クライアント ID が作成されます(のちほどプログラムに記述します)。「完了」をクリックします。

5. API キーの作成

次に「認証情報」から「✙ 認証情報を作成」をクリックし、「API キー」をクリックします。

しばらく待つと、API キーが作成されます(プログラムに記述します)。「閉じる」をクリックします。

最後に「OAuth 同意画面」から「アプリを公開」をクリックし、「確認」ボタンをクリックしてテスト環境から本番環境へ切り替えます。

プログラム

今回使用するプログラム

URL 指定で追加
  • https://apis.google.com/js/api.js
  • https://accounts.google.com/gsi/client
  • https://js.cybozu.com/spinjs/2.3.2/spin.min.js
  • https://js.cybozu.com/encodingjs/2.0.0/encoding.min.js
  • https://js.cybozu.com/kintone-rest-api-client/3.1.9/KintoneRestAPIClient.min.js
アップロードして追加
  • kintone-gmail.js
    Google API の認証情報の設定を記述している為、環境に合わせて修正する部分があります( 後述
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/* global gapi */
/* global google */
/* global Encoding */
/* global KintoneRestAPIClient */

(() => {
  'use strict';

  // ログインのフラグ
  let tokenClient = false,
    isInitializeGapi = false,
    isInitializeGsi = false;

  // 設定
  const AppSetting = {
    CLIENT_ID: 'クライアントID',
    API_KEY: 'APIキー',
    DISCOVERY_DOC: 'https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest',
    SCOPES: 'https://mail.google.com/',
    fieldsCode: {
      attachment: 'attachment',
      bcc: 'bcc',
      cc: 'cc',
      content: 'message',
      dateTime: 'Date_and_time',
      from: 'from',
      labels: 'labels_id',
      mailAccount: 'email_account',
      messageID: 'message_id',
      owner: 'owner',
      subject: 'subject',
      threadID: 'thread_id',
      to: 'to'
    },
    profile: {emailAddress: ''},
    extensionProhibited: [
      'ADE', 'ADP', 'BAT', 'CHM', 'CMD', 'COM',
      'CPL', 'DLL', 'DMG', 'EXE', 'HTA', 'INS',
      'ISP', 'JAR', 'JS', 'JSE', 'LIB', 'LNK',
      'MDE', 'MSC', 'MSI', 'MSP', 'MST', 'NSH',
      'PIF', 'SCR', 'SCT', 'SHB', 'SYS', 'VB',
      'VBE', 'VBS', 'VXD', 'WSC', 'WSF', 'WSH'
    ],
    maxEmailSize: 5 * 1024 * 1024, // (byte) ~5MB
    maxMessagesForGet: 45,
  };

  // スピナーを動作させる関数
  const showSpinner = ()=> {
    // 要素作成等初期化処理
    if (document.getElementsByClassName('kintone-spinner').length === 0) {
      // スピナー設置用要素と背景要素の作成
      const spnDiv = document.createElement('div');
      spnDiv.id = 'kintone-spin';
      spnDiv.classList.add('kintone-spinner');
      const spinBgDiv = document.createElement('div');
      spinBgDiv.id = 'kintone-spin-bg';
      spinBgDiv.classList.add('kintone-spinner');

      // スピナー用要素をbodyにappend
      document.body.appendChild(spnDiv);
      document.body.appendChild(spinBgDiv);

      // スピナーに対するオプション設定
      const opts = {
        lines: 11, // The number of lines to draw
        length: 38, // The length of each line
        width: 17, // The line thickness
        radius: 45, // The radius of the inner circle
        scale: 1, // Scales overall size of the spinner
        corners: 1, // Corner roundness (0..1)
        speed: 1, // Rounds per second
        rotate: 0, // The rotation offset
        animation: 'spinner-line-fade-more', // The CSS animation name for the lines
        direction: 1, // 1: clockwise, -1: counterclockwise
        color: '#000', // CSS color or array of colors
        fadeColor: 'transparent', // CSS color or array of colors
        top: '50%', // Top position relative to parent
        left: '50%', // Left position relative to parent
        shadow: '0 0 1px transparent', // Box-shadow for the lines
        zIndex: 2000000000, // The z-index (defaults to 2e9)
        className: 'spinner', // The CSS class to assign to the spinner
        position: 'absolute', // Element positioning
      };

      // スピナーを作動
      new Spinner(opts).spin(document.getElementById('kintone-spin'));
    }

    // スピナー始動(表示)
    document.getElementById('kintone-spin-bg').style.display = 'block';
    document.getElementById('kintone-spin').style.display = 'block';
  };

  // スピナーを停止させる関数
  const hideSpinner = () => {
  // スピナー停止(非表示)
    document.getElementById('kintone-spin-bg').style.display = 'none';
    document.getElementById('kintone-spin').style.display = 'none';
  };

  // Googleログイン&ログアウト
  const loadGapi = () => {
    gapi.load('client', intializeGapiClient);
  };

  const intializeGapiClient = async () => {
    await gapi.client.init({
      apiKey: AppSetting.API_KEY,
      discoveryDocs: [AppSetting.DISCOVERY_DOC],
    });
    isInitializeGapi = true;
    checkBeforeStart();
  };

  const loadGsi = () => {
    tokenClient = google.accounts.oauth2.initTokenClient({
      client_id: AppSetting.CLIENT_ID,
      scope: AppSetting.SCOPES,
      callback: '',
    });
    isInitializeGsi = true;
    checkBeforeStart();
  };

  // ログイン準備ができたらログインボタン表示
  const checkBeforeStart = () => {
    if (isInitializeGapi && isInitializeGsi) {
      document.getElementById('loginButton').style.visibility = 'visible';
    }
  };

  // Googleログインボタンクリック
  const handleLoginClick = () => {
    tokenClient.callback = async (resp) => {
      if (resp.error !== undefined) {
        throw resp;
      }
      document.getElementById('logoutButton').style.visibility = 'visible';
      document.getElementById('getMailButton').style.visibility = 'visible';
      document.getElementById('loginButton').innerText = 'Refresh';

      // プロフィールデータ取得
      AppSetting.profile.emailAddress = (await gapi.client.gmail.users.getProfile({userId: 'me'})).result.emailAddress;

    };
    if (gapi.client.getToken() === null) {
      tokenClient.requestAccessToken({prompt: 'consent'});
    } else {
      tokenClient.requestAccessToken({prompt: ''});
    }
  };

  // Googleログアウトボタンクリック
  const handleLogoutClick = () => {
    const token = gapi.client.getToken();
    if (token !== null) {
      google.accounts.oauth2.revoke(token.access_token);
      gapi.client.setToken('');
      document.getElementById('loginButton').innerText = 'Authorize';
      document.getElementById('logoutButton').style.visibility = 'hidden';
      document.getElementById('getMailButton').style.visibility = 'hidden';
    }
  };


  // メール送信
  const parseRecordDataToEmailData = (record) => {
    const result = {};
    for (const key in AppSetting.fieldsCode) {
      if (Object.prototype.hasOwnProperty.call(AppSetting.fieldsCode, key)) {
        const fieldCode = AppSetting.fieldsCode[key];
        result[key] = record[fieldCode].value;
      }
    }
    return result;
  };

  // 送信メールBase64URLエンコード
  const encodeSender = (senderString) => {
    const senderArray = String(senderString).trim().split(',');
    const senderResult = [];
    senderArray.forEach((sender) => {
      const patternSender = new RegExp(/(.*)<(.*)>/);
      const result = patternSender.exec(sender.trim());
      let email = '';
      let emailEncoded = '';
      if (result !== null && result.length === 3) {
        emailEncoded = encodeUTF8(result[1]) + ' <' + result[2] + '>';
        email = result[2];
      } else {
        emailEncoded = sender;
        email = sender;
      }
      if (email === '') {
        throw new Error('Emailアドレスが不正です。');
      }
      senderResult.push(emailEncoded);
    });
    return senderResult.join(',');
  };
  const encodeStringToBase64 = (string) => {
    return Encoding.base64Encode((new TextEncoder()).encode(string));
  };
  const encodeUTF8 = (string) => {
    return '=?UTF-8?B?' + encodeStringToBase64(string) + '?=';
  };
  const getByteOfString = (string) => {
    return encodeURI(string).split(/%..|./).length - 1;
  };
  const mineMessage = (data) => {
    const boundary = 'kintoneBoundaryData';
    const mineData = [];
    mineData.push('Content-Type: multipart/mixed; charset="UTF-8"; boundary="' + boundary + '"\r\n');
    mineData.push('MIME-Version: 1.0\r\n');
    if (data.from) {
      mineData.push('From: ' + encodeSender(data.from) + '\r\n');
    }
    if (data.to) {
      mineData.push('To: ' + encodeSender(data.to) + '\r\n');
    }
    if (data.cc) {
      mineData.push('Cc: ' + encodeSender(data.cc) + '\r\n');
    }
    if (data.bcc) {
      mineData.push('Bcc: ' + encodeSender(data.bcc) + '\r\n');
    }
    if (data.subject) {
      mineData.push('Subject: ' + encodeUTF8(data.subject) + '\r\n\r\n');
    }
    if (data.content) {
      mineData.push('--' + boundary + '\r\n');
      mineData.push('Content-Type: text/html; charset="UTF-8"\r\n');
      mineData.push('MIME-Version: 1.0\r\n');
      mineData.push('Content-Transfer-Encoding: 8bit\r\n\r\n');
      mineData.push(data.content + '\r\n\r\n');
    }
    if (data.attachment) {
      data.attachment.forEach((attach) => {
        mineData.push('--' + boundary + '\r\n');
        mineData.push('Content-Type: ' + attach.contentType + '\r\n');
        mineData.push('MIME-Version: 1.0\r\n');
        mineData.push('Content-Transfer-Encoding: base64\r\n');
        mineData.push('Content-Disposition: attachment; filename="' + attach.fileKey + '"');
      });
    }
    mineData.push('--' + boundary + '--');
    return mineData.join('');
  };
  // 添付ファイルの拡張子を返す
  const getFileExtension = (fileName) => {
    if (!fileName) {
      return '';
    }
    return String(fileName.split('.').pop()).toUpperCase();
  };
  // レコードから送信メールデータを作成する
  const makeMailData = (mailData) => {
    let mineEmail = mineMessage(mailData);
    let hasAttachment = false;
    let mineEmailByte = getByteOfString(mineEmail);
    if (mailData.attachment && Array.isArray(mailData.attachment) && mailData.attachment.length > 0) {
      hasAttachment = true;
      mailData.attachment.forEach((att) => {
        // 添付ファイルの拡張子チェック
        const fileExt = getFileExtension(att.name);
        if (AppSetting.extensionProhibited.indexOf(fileExt) >= 0) {
          throw new Error(`${att.name}は添付できない拡張子のファイルです`);
        }
        // ファイルサイズ計算
        mineEmailByte += Number(att.size);
        mineEmailByte -= getByteOfString(att.fileKey);
        mineEmailByte += getByteOfString(att.name + '\r\n\r\n\r\n\r\n');
      });
    }
    if (mineEmailByte >= AppSetting.maxEmailSize) {
      throw new Error('メールの送信可能サイズを超えています。');
    }
    // 添付ファイルがなければこの時点のmineEmailを返す
    if (hasAttachment === false) {
      return mineEmail;
    }
    // 添付ファイルが有れば、mineEmailに添付ファイルデータ分付け足して返す
    return downloadAttachments(mailData.attachment)
      .then((mailAttachments) => {
        mailAttachments.forEach((att) => {
          mineEmail = mineEmail.replace('"' + att.fileKey + '"', '"' + att.name + '"\r\n\r\n' + att.contentBytes + '\r\n\r\n');
        });
        return mineEmail;
      });
  };

  // kintoneの添付ファイルをダウンロードしてファイルデータをエンコードしたものを返す
  const downloadAttachments = (attachments) => {
    const attachmentPromise = [];
    for (let i = 0; i < attachments.length; i++) {
      attachmentPromise.push(downloadAttachment(attachments[i]));
    }
    return kintone.Promise.all(attachmentPromise)
      .catch((error) => {
        console.log(error.message);
      });
  };

  // kintoneの添付ファイルをダウンロードしてエンコードする
  const downloadAttachment = (kintoneFileData) => {
    const url = '/k/v1/file.json?fileKey=' + kintoneFileData.fileKey;
    return new kintone.Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      xhr.responseType = 'arraybuffer';
      xhr.onload = () => {
        kintoneFileData.contentBytes = encodeBufferToBase64(xhr.response);
        resolve(kintoneFileData);
      };
      xhr.onerror = (e) => {
        reject(e);
      };
      xhr.send();
    });
  };

  // エンコード
  const encodeBufferToBase64 = (arraybuffer) => {
    let binary = '';
    const bytes = new Uint8Array(arraybuffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  };

  // メール送信する
  const sendMail = async (record) => {
    try {
      // スピナー表示
      showSpinner();
      const emailAddress = (await gapi.client.gmail.users.getProfile({userId: 'me'})).result.emailAddress;
      const mineEmail = await makeMailData(parseRecordDataToEmailData(record));
      const rawdata = Encoding.base64Encode((new TextEncoder()).encode(mineEmail)).replaceAll('/', '_').replaceAll('+', '-');
      const dataEmailResponse = await gapi.client.gmail.users.messages.send({
        userId: 'me',
        resource: {raw: rawdata}
      });

      // メール送信後にレコードを更新する
      const updateRecordData = {};
      updateRecordData[AppSetting.fieldsCode.messageID] = {
        value: dataEmailResponse.result.id
      };
      updateRecordData[AppSetting.fieldsCode.threadID] = {
        value: dataEmailResponse.result.threadId
      };
      updateRecordData[AppSetting.fieldsCode.labels] = {
        value: dataEmailResponse.result.labelIds ? dataEmailResponse.result.labelIds.join(',') : ''
      };
      updateRecordData[AppSetting.fieldsCode.mailAccount] = {
        value: emailAddress
      };
      updateRecordData[AppSetting.fieldsCode.owner] = {
        value: [{
          code: kintone.getLoginUser().code,
          type: 'USER'
        }]
      };
      updateRecordData[AppSetting.fieldsCode.from] = {
        value: emailAddress
      };
      // レコード更新
      await kintone.api('/k/v1/record.json', 'PUT', {
        app: kintone.app.getId(),
        id: kintone.app.record.getId(),
        record: updateRecordData
      });
      location.reload();
      alert('メール送信完了');
    } catch (error) {
      console.log(error.message);
      alert('メール送信失敗');
    } finally {
      // スピナー非表示
      hideSpinner();
    }
  };

  // メール受信
  const getBodyMessage = (dataParts, type) => {
    for (let index = 0; index < dataParts.length; index++) {
      const bodyPart = dataParts[index];
      if (bodyPart.parts) {
        return getBodyMessage(bodyPart.parts, type);
      }
      const body = bodyPart.body.data || '';
      if (bodyPart.mimeType === type) {
        return body;
      }
    }
    return '';
  };

  // メールのヘッダデータ取得
  const getHeaders = (arrayKeys, payloadData) => {
    const result = {};
    if (!arrayKeys || !Array.isArray(arrayKeys)) {
      return result;
    }
    for (let i = 0; i < payloadData.headers.length; i++) {
      if (arrayKeys.indexOf(payloadData.headers[i].name) !== -1) {
        result[payloadData.headers[i].name.toLowerCase()] = payloadData.headers[i].value;
      }
    }
    return result;
  };

  // メールの添付ファイルを取得
  const getAttachmentFiles = (payloadData) =>{
    const fs = [];
    if (!payloadData.parts) {
      return fs;
    }

    function getFiles(dataParts) {
      dataParts.forEach((part) => {
        if (part.parts) {
          return getFiles(part.parts);
        }
        if (part.filename !== '' && part.body.attachmentId) {
          fs.push(part);
        }
        return true;
      });
    }

    getFiles(payloadData.parts);
    return fs;
  };

  // 受信メールから新規レコードを作成
  const makeKintonMailData = async (mid) => {
    const mailData = await gapi.client.gmail.users.messages.get({
      userId: 'me',
      id: mid,
    });

    const result = {
      headers: getHeaders(['From', 'To', 'Cc', 'Bcc', 'Subject'], mailData.result.payload),
      fileKeys: [],
      mailInfo: {
        id: mid,
        threadId: mailData.result.threadId,
        labelIds: mailData.result.labelIds,
        date: mailData.result.internalDate,
      },
      profile: {
        emailAddress: AppSetting.profile.emailAddress,
      }
    };

    result.files = getAttachmentFiles(mailData.result.payload);

    if (!mailData.result.payload.parts) {
      result.body = decodeMessage(mailData.result.payload.body.data, mailData) || '';
    } else {

      const msgBody = getBodyMessage(mailData.result.payload.parts, 'text/html') || getBodyMessage(mailData.result.payload.parts, 'text/plain');
      result.body = decodeMessage(msgBody, mailData);
    }
    return addMailIntoKintone(result.mailInfo, result.headers, result.body, result.profile, result.files);
  };

  // kintoneにPOSTするリクエストボディのrecord情報作成
  const addMailIntoKintone = async (mailInfo, headers, body, profile, files) => {
    const kintoneRecord = {};
    kintoneRecord[AppSetting.fieldsCode.subject] = {
      value: headers.subject
    };
    kintoneRecord[AppSetting.fieldsCode.from] = {
      value: headers.from
    };
    kintoneRecord[AppSetting.fieldsCode.to] = {
      value: headers.to
    };
    kintoneRecord[AppSetting.fieldsCode.cc] = {
      value: headers.cc || ''
    };
    kintoneRecord[AppSetting.fieldsCode.bcc] = {
      value: headers.bcc || ''
    };
    const content = body;
    kintoneRecord[AppSetting.fieldsCode.content] = {
      value: content
    };
    kintoneRecord[AppSetting.fieldsCode.dateTime] = {
      value: (new Date(Number(mailInfo.date))).toISOString()
    };
    kintoneRecord[AppSetting.fieldsCode.threadID] = {
      value: mailInfo.threadId
    };
    kintoneRecord[AppSetting.fieldsCode.messageID] = {
      value: mailInfo.id
    };
    kintoneRecord[AppSetting.fieldsCode.labels] = {
      value: getLabelsStringForStorage(mailInfo.labelIds)
    };
    kintoneRecord[AppSetting.fieldsCode.mailAccount] = {
      value: profile.emailAddress
    };

    kintoneRecord[AppSetting.fieldsCode.owner] = {
      value: [{
        code: kintone.getLoginUser().code,
        type: 'USER'
      }]
    };

    if (files && files.length > 0) {
      kintoneRecord[AppSetting.fieldsCode.attachment] = {
        value: await uploadFileToKintone(mailInfo.id, files, 0, []),
      };
    }

    return addNewRecord(kintoneRecord);
  };

  // POSTする
  const addNewRecord = (kintoneRecord) => {
    return kintone.api('/k/v1/record.json', 'POST', {
      app: kintone.app.getId(),
      record: kintoneRecord
    });
  };

  const getLabelsStringForStorage = (labelList) => {
    return labelList.filter((item) => {
      return ['INBOX', 'SENT'].indexOf(item) > -1;
    }).join(', ');
  };

  // メールの添付ファイルをkintoneに保存できるようにエンコードする
  const encodeAttachmentBase64ToBlob = (base64String, contentType) => {
    const binary = decodeAttachment(base64String);
    const blob = new Blob([binary], {
      type: (contentType || 'octet/stream') + ';charset=utf-8;'
    });
    return blob;
  };

  // 添付ファイルをkintoneにアップロードする
  const uploadFileToKintone = async (messageID, files, index, kintoneFilesKey) => {
    const file = files[index];

    const attachment = await gapi.client.gmail.users.messages.attachments.get({
      id: file.body.attachmentId,
      messageId: messageID,
      userId: 'me',
    });

    // Create form file
    const formFile = new FormData();
    const blobFileAttachment = encodeAttachmentBase64ToBlob(attachment.result.data, file.mimeType);
    formFile.append('__REQUEST_TOKEN__', kintone.getRequestToken());
    formFile.append('file', blobFileAttachment, file.filename);

    const kintoneFileResponse = await uploadFile(kintone.api.url('/k/v1/file.json'), 'POST', formFile);
    kintoneFilesKey.push(window.JSON.parse(kintoneFileResponse.response));

    // POST files to kintone
    if (index + 1 < files.length) {
      return uploadFileToKintone(messageID, files, index + 1, kintoneFilesKey);
    }
    return kintoneFilesKey;
  };

  // kintone にファイルをアップロードする
  const uploadFile = (url, method, formData, headers) => {
    return new kintone.Promise((resolve, reject) => {
      const xhrRequest = new XMLHttpRequest();
      xhrRequest.open(method, url);
      if (headers) {
        headers.forEach((header) => {
          if (header.key && header.value) {
            xhrRequest.setRequestHeader(header.key, header.value);
          }
        });
      }
      xhrRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      xhrRequest.onload = function() {
        if (xhrRequest.status === 200) {
          resolve(this);
        } else {
          reject(xhrRequest);
        }
      };
      xhrRequest.send(formData);
    });
  };

  // メールの本文データをデコード
  const decodeMessage = (msg)=>{
    return new TextDecoder().decode(new Uint8Array(Encoding.base64Decode(msg.replaceAll('_', '/').replaceAll('-', '+'))));
  };

  // メールの添付ファイルをデコード
  function decodeAttachment(stringEncoded) {
    return new Uint8Array(Encoding.base64Decode(stringEncoded.replaceAll('_', '/').replaceAll('-', '+')));
  }

  // kintoneに保存していない受信メールのリストを取得
  const getPageOfMessages = async (allMsgList, dataRequest) =>{
    const msgList = await gapi.client.gmail.users.messages.list(dataRequest);
    if (msgList.result.nextPageToken) {
      const nextDataRequest = dataRequest;
      nextDataRequest.pageToken = msgList.result.nextPageToken;
      return getPageOfMessages(allMsgList.concat(msgList.result.messages), nextDataRequest);
    }
    return allMsgList.concat(msgList.result.messages);
  };

  // メール受信
  const getMails = async () => {
    try {
      // スピナー表示
      showSpinner();
      // メールリストから受診していないメールIDを取得
      const allList = await getPageOfMessages([], {
        userId: 'me',
        maxResults: 500,
        includeSpamTrash: false,
      });

      // メールが1件もなければエラー
      if (!allList || allList.length === 0) {
        throw new Error('No messages found.');
      }

      const rmsgIdArry = [];

      // レコード全件取得
      const client = new KintoneRestAPIClient();
      const allRecords = await client.record.getAllRecords({app: kintone.app.getId(), fields: [AppSetting.fieldsCode.messageID]});

      allRecords.forEach((r) => {
        rmsgIdArry.push(r[AppSetting.fieldsCode.messageID].value);
      });

      // まだ受診していないメールIDを最大45件取得
      const getMailIds = allList.filter(i => rmsgIdArry.indexOf(i.id) === -1).slice(0, AppSetting.maxMessagesForGet);

      const results = [];
      getMailIds.forEach(m=>{
        results.push(makeKintonMailData(m.id));
      });

      await Promise.all(results)
        .then((resp)=>{
          alert('メール受信成功!');
        });
    } catch (error) {
      console.log(error.message);
      alert('メール受信失敗');
    } finally {
      // スピナー非表示
      hideSpinner();
      location.reload();
    }
  };


  // レコード一覧
  kintone.events.on('app.record.index.show', (event) => {

    const sp = kintone.app.getHeaderMenuSpaceElement();
    // ボタンを作る
    const loginButton = document.createElement('button');
    loginButton.id = 'loginButton';
    const logoutButton = document.createElement('button');
    logoutButton.id = 'logoutButton';
    const getMailButton = document.createElement('button');
    getMailButton.id = 'getMailButton';
    // ボタンに表示したいテキスト
    loginButton.textContent = 'Gmailログイン';
    logoutButton.textContent = 'Gmailログアウト';
    getMailButton.textContent = 'メール受信';
    // スペースフィールドにボタンを追加する
    sp.appendChild(loginButton);
    sp.appendChild(logoutButton);
    sp.appendChild(getMailButton);
    loginButton.style.visibility = 'hidden';
    logoutButton.style.visibility = 'hidden';
    getMailButton.style.visibility = 'hidden';
    loginButton
      .addEventListener('click', handleLoginClick);
    logoutButton
      .addEventListener('click', handleLogoutClick);
    getMailButton
      .addEventListener('click', getMails);

    // ログイン準備
    loadGapi();
    loadGsi();
    return event;
  });

  // レコード詳細
  kintone.events.on('app.record.detail.show', (event) => {

    const sp = kintone.app.record.getHeaderMenuSpaceElement();
    // ボタンを作る
    const loginButton = document.createElement('button');
    loginButton.id = 'loginButton';
    const logoutButton = document.createElement('button');
    logoutButton.id = 'logoutButton';
    const sendMailButton = document.createElement('button');
    sendMailButton.id = 'getMailButton';
    // ボタンに表示したいテキスト
    loginButton.textContent = 'Gmailログイン';
    logoutButton.textContent = 'Gmailログアウト';
    sendMailButton.textContent = 'メール送信';
    // スペースフィールドにボタンを追加する
    sp.appendChild(loginButton);
    sp.appendChild(logoutButton);
    sp.appendChild(sendMailButton);
    loginButton.style.visibility = 'hidden';
    logoutButton.style.visibility = 'hidden';
    sendMailButton.style.visibility = 'hidden';
    loginButton
      .addEventListener('click', handleLoginClick);
    logoutButton
      .addEventListener('click', handleLogoutClick);
    sendMailButton
      .addEventListener('click', sendMail.bind(null, event.record));

    // ログイン準備
    loadGapi();
    loadGsi();
    return event;
  });

  kintone.events.on([
    'app.record.index.edit.show',
    'app.record.edit.show',
    'app.record.create.show'
  ],
  (event) =>{
    event.record[AppSetting.fieldsCode.from].disabled = true;
    if (event.type === 'app.record.create.show') {
      event.record[AppSetting.fieldsCode.from].value = '';
      event.record[AppSetting.fieldsCode.threadID].value = '';
      event.record[AppSetting.fieldsCode.labels].value = '';
      event.record[AppSetting.fieldsCode.mailAccount].value = '';
      event.record[AppSetting.fieldsCode.messageID].value = '';
      event.record[AppSetting.fieldsCode.owner].value = [{
        code: kintone.getLoginUser().code
      }];
    }
    return event;
  });

})();

プログラムの修正

kintone-gmail.js に Google APIの認証情報の設定 でメモしておいたクライアント ID と API キーを記述します。

14
15
16
17
18
19
// 設定
const AppSetting = {
  CLIENT_ID: 'クライアントID',
  API_KEY: 'APIキー',
  // 省略..
};

プログラムの配置

これらのプログラムを「アプリの設定 > JavaScript/CSS でカスタマイズ」下に配置します。

動作確認

メール受信

kintone アプリのレコード一覧画面を開きます。『Gmail にログイン』というボタンが表示されるので、ボタンをクリックします。

OAuth 認証画面が表示されるので、 Google APIの認証情報の設定 で準備した Google アカウントでログインします。

ログインに成功した場合、先ほどまで『Gmail にログイン』だけだったボタンは『Refresh』『Gmail ログアウト』『メール受信』の 3 つのボタンに変わります。

『メール受信』ボタンをクリックすることで、メールデータを kintone のレコードに登録します。

Gmail のメールが kintone に登録されます。
すでに取得済み(kintone に登録済み)のメールは登録されません。

メール送信

kintone のレコード追加を選択し、必要なフィールドに記入します。
本文は kintone のリッチエディターフィールドを利用しているので、文字色や文字サイズの変更などもできます。

レコード保存後、メール受信の場合と同様に Gmail にログインすると、レコード詳細画面の上部に『メール送信』ボタンが表示されます。
『メール送信』ボタンをクリックすればメールを送信できます。

メールが送信できたことを確認できます。

information

この Tips は、2022 年 9 月版 kintone で動作を確認しています。