iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎃

Automatically record credit card usage to Google Sheets via notification emails

に公開
2024/08/16

Purpose

I want to manage credit card usage information in a spreadsheet so that I can check the details directly.

Prerequisites

Use a credit card that sends usage amounts via email immediately.
When an email arrives, use that information to record it in a spreadsheet.
Use GAS (Google Apps Script) and Google Sheets.

Visual

Payment

↓
Email arrives

↓
Automatically recorded in a spreadsheet

Implementation

Structure

GoogleDrive/
    └ MoneyPortal/
        ├ MoneyPortal # Google Spread Sheet
        └ CheckMail # GAS

Create necessary sheets in Google Sheets

Create a sheet named message and enter the following values from A1 to H1.

Cell Address Value Purpose
A1 message_id Gmail message ID
B1 date Card usage date and time
C1 value Card usage amount
D1 shop Store name
E1 card_name Card name
F1 date_timestamp Timestamp of card usage date (date)
G1 updated Timestamp at the time of recording
H1 is_notified Write flag to the record sheet

GAS Setup

Set Script Properties

Create a new GAS file and set the following script property.
Key: SPREAD_SHEET_ID
Value: The ID of the spreadsheet you just created.

Import Libraries

The following libraries are used.

GAS Code

Logger.gs

Configure the basic settings for BetterLog.

Logger.gs
const Logger = (() => {
    const ssId = PropertiesService
        .getScriptProperties().getProperty('SPREAD_SHEET_ID');
    // Log output destination is SPREAD_SHEET_ID
    const _logger = BetterLog.useSpreadsheet(ssId);
    // Specify the log format
    _logger.DATE_TIME_LAYOUT = "yyyy-MM-dd kk:mm:ss.SS Z '[CheckMail]'";
    return _logger;
})();

checkMail.gs

Detects new emails and records their content to the message sheet.
There are values that need to be configured for each environment.
The configuration items are as follows:

  1. GAMIL_APP_QUERY
    The query to retrieve only usage notification emails in Gmail. For example, if usage notification emails are sorted into a label named "XXXX Card" in Gmail, this value would be the string "label:XXXX Card".
  2. CARD_NAME
    The name of the target card. This will be recorded in the card_name field of the message sheet. For example, the string "XXXX Card".
  3. Pattern for extracting the usage date
    The regular expression to get the usage date from the text in the email. For example, if there is a string like "利用日:2024/08/11 16:50" in the email, the regular expression would be /利用日:(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2})/. Use the email content check program to investigate the strings inside the email.
  4. Pattern for extracting the usage amount
    The regular expression to get the usage amount from the text in the email. For example, if there is a string like "利用金額:192円" in the email, the regular expression would be /(?<=利用金額:)(\b\d{1,3}(,\d{3})*\b)(?=円)/. Use the email content check program to investigate the strings inside the email.
  5. Pattern for extracting the merchant
    The regular expression to get the merchant from the text in the email. For example, if there is a string like "利用先:SEVEN-ELEVEN" in the email, the regular expression would be /利用先:(.+)/. Use the email content check program to investigate the strings inside the email.
checkMail.gs
function checkMail() {
    const ssId = PropertiesService
        .getScriptProperties().getProperty('SPREAD_SHEET_ID');
    const SheetSQL = SpreadSheetsSQL.open(ssId, 'message');

    // <Configuration Item 1> Gmail Query
    // Query to retrieve usage notification emails in Gmail
    const GAMIL_APP_QUERY = 'label:XXXXカード';
    // <Configuration Item 2> Card Name
    // Card name to be entered in the card_name of the message sheet or method of the record sheet
    const CARD_NAME = 'XXXXCard';
    // Number of threads to retrieve from Gmail search results
    const GMAIL_SREAD_LIMIT = 3;

    const threads = GmailApp.search(GAMIL_APP_QUERY, 0, GMAIL_SREAD_LIMIT);
    // Array of message_id. Used to determine if the email is new
    const msgIdList = SheetSQL.select(['message_id']).result()
        .map((obj) => obj.message_id);

    for (let thread of threads) {
    for (let message of thread.getMessages()) {
    // Processing per email -----------------------------
    // ===== Program for checking email content =====
    // Used to set configuration items 3 to 5. Delete after configuration.
    console.log(message.getPlainBody()); continue;
    // =====================================
    // Message ID
    const msgId = message.getId();
    console.log(msgId);
    // Ignore if already written
    // Newer msgIds come later in the msgIdList
    if (msgIdList.lastIndexOf(msgId) !== -1) continue;

    // Email body
    const mBody = message.getPlainBody();

    // Information retrieval
    // Extract necessary information from the email body using pattern matching
    const trnsDate = (function (t) {
        // <Configuration Item 3> Pattern for extracting usage date
        const regexp = new RegExp(/利用日:(\d{4}\/\d{2}\/\d{2} \d{2}:\d{2})/);
        const match = regexp.exec(t);
        if (!match) return '';
        // This email only contains YYYY/MM/DD hh:mm up to the minute
        if (match !== null) return match[1] + ':00';
        else return '';
    })(mBody);

    const trnsValue = (function (t) {
        // <Configuration Item 4> Pattern for extracting usage amount
        const regexp = new RegExp(/(?<=利用金額:)(\b\d{1,3}(,\d{3})*\b)(?=円)/);
        const match = t.match(regexp);
        // Since the number is separated by commas, remove them and convert to a number
        if (match !== null) return parseInt(match[0].replace(",", "")); 
        else return 0;
    })(mBody);

    const trnsShop = (function (t) {
        // <Configuration Item 5> Pattern for extracting merchant
        const regexp = new RegExp(/利用先:(.+)/);
        const match = regexp.exec(t);
        if (match !== null) return match[1];
        else return "";
    })(mBody);

    // Set current time when trnsDate is empty
    const now = new Date();
    const trnsDateObj = (trnsDate === '') ? now : new Date(trnsDate);

    // Write
    SheetSQL.insertRows([{
        message_id: msgId,
        date: trnsDate,
        value: trnsValue,
        shop: trnsShop,
        card_name: CARD_NAME,
        date_timestamp: trnsDateObj.getTime(),
        updated: now.getTime(),
        is_notified: 'no',
    }]);

    // Mark the message as read
    message.markRead();
    // -----------------------------------------
    } // End of for (let thread of threads)
    } // End of for (let message of thread.getMessages())
}

Execution Settings

  1. Configure the settings in checkMail.gs in the previous section appropriately.
  2. Run checkMail for the first time to assign permissions and other authorizations.
  3. Finally, set up a trigger to run the checkMail function every 5 minutes, and you are all set.

Discussion