9ml

Gmailからスプレッドシートにテキストを抽出する

function getEmailToSpreadSheet() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var threads = GmailApp.search('from:kantohire@gmail.com');
  var startRow = sheet.getLastRow() + 1;

  sheet.getRange(1,1).setValue('号車');
  sheet.getRange(1,2).setValue('決済日時');
  sheet.getRange(1,3).setValue('金額(円)');
  sheet.getRange(1,4).setValue('車番');

  threads.forEach(function(thread) {
    // タイトルと本文を抜き出す
    var message = thread.getMessages()[0];
    var subject = message.getSubject();
    var body = message.getPlainBody();

    // 号車
    var carnumberMatch = body.match(/[0-9]+号車/);
    var carnumber = carnumberMatch ? carnumberMatch[0] : '号車なし';

    // 金額
    var amountMatch = body.match(/[0-9]+円/);
    var amount = amountMatch ? amountMatch[0] : '金額なし';
    amount = amount.replace(/円/, '').trim();

    // 決済日時
    var paymentdateMatch = body.match(/決済日時([\s\S]*?)詳細を確認する/);
    var paymentdate = paymentdateMatch ? paymentdateMatch[0] : '決済日時なし';
    paymentdate = paymentdate.replace(/決済日時|詳細を確認する/g, '').trim();

    // 車番
    switch (carnumber) {
      case "1号車":
        taxi = 1033;
        break;
      case "2号車":
        taxi = 408;
        break;
      case "3号車":
        taxi = 958;
        break;
      case "4号車":
        taxi = 4444444444;
        break;
      case "5号車":
        taxi = 1102;
        break;
      case "6号車":
        taxi = 1568;
        break;
      case "7号車":
        taxi = 1402;
        break;
      case "8号車":
        taxi = 1140;
        break;
      case "9号車":
        taxi = 9999999999;
        break;
      case "10号車":
        taxi = 1574;
        break;
      case "11号車":
        taxi = 407;
        break;
      case "12号車":
        taxi = 2222222222;
        break;
      case "13号車":
        taxi = 1206;
        break;
      case "14号車":
        taxi = 1488;
        break;
      case "15号車":
        taxi = 961;
        break;
      default:
        taxi = "車番なし";
        break;
    }

    sheet.getRange(startRow, 1).setValue(carnumber);
    sheet.getRange(startRow, 2).setValue(paymentdate);
    sheet.getRange(startRow, 3).setValue(amount);
    sheet.getRange(startRow, 4).setValue(taxi);

    // メールをゴミ箱に移動する
    thread.moveToTrash();

    startRow++;
  });
}
ホームに戻る