n8n_Auntomation
【n8n自動化】GmailからGoogleスプレッドシートへ自動転記する方法|週5-10時間削減
1. Google Cloud APIのリンク
!
- Google Cloud APIにアクセスして 「ログイン」or 「無料で利用開始」をクリック
- 遷移先で自身のメールアドレスを入力
2. Javascript
- **YouTube 「【n8n自動化】GmailからGoogleスプレッドシートへ自動転記する方法|週5-10時間削減」で使用したJavascriptです。
// Gmail データから売上情報を抽出してGoogle Sheets用に変換
const items = [];
try {
for (const item of $input.all()) {
const data = item.json;
// Fromからメールアドレスを抽出
let fromEmail = 'unknown@domain.com';
if (data.From) {
const emailMatch = data.From.match(/<([^>]+)>|([^\s<>]+@[^\s<>]+)/);
fromEmail = emailMatch ? (emailMatch[1] || emailMatch[2]) : data.From;
}
// Subjectを取得
const subject = data.Subject || 'No Subject';
// Snippetから情報を抽出
let snippet = data.snippet || '';
console.log('=== ORIGINAL SNIPPET ===');
console.log(snippet);
// 日付を抽出し、年月日に分割
let year = '', month = '', day = '';
const dateMatch = snippet.match(/\[日時\](\d{4})-(\d{2})-(\d{2})/);
if (dateMatch) {
year = dateMatch[1];
month = dateMatch[2];
day = dateMatch[3];
} else {
const today = new Date();
year = today.getFullYear().toString();
month = String(today.getMonth() + 1).padStart(2, '0');
day = String(today.getDate()).padStart(2, '0');
}
console.log('Date extracted:', { year, month, day });
// 商品情報を抽出
let productSection = '';
if (snippet.includes('[商品]')) {
productSection = snippet.split('[商品]')[1];
} else if (snippet.includes('商品')) {
const parts = snippet.split('商品');
if (parts.length > 1) {
productSection = parts[1];
}
}
console.log('=== PRODUCT SECTION ===');
console.log(productSection);
if (productSection) {
// より精密な正規表現(重複を避ける)
// 「商品名 + 価格 + ¥価格 + x + 数量 + = + ¥小計」の完全パターンのみマッチ
const productPattern = /([^•\n=¥]+?)\s+価格\s+¥(\d+(?:,\d{3})*)\s+x\s*(\d+)\s*=\s*¥(\d+(?:,\d{3})*)/g;
let match;
const foundProducts = new Set(); // 重複チェック用
while ((match = productPattern.exec(productSection)) !== null) {
const productName = match[1].trim();
const unitPrice = parseInt(match[2].replace(/,/g, ''));
const quantity = parseInt(match[3]);
const subtotal = parseInt(match[4].replace(/,/g, ''));
// 重複チェック(商品名 + 数量の組み合わせ)
const productKey = `${productName}_${quantity}`;
if (!foundProducts.has(productKey)) {
foundProducts.add(productKey);
console.log('UNIQUE PRODUCT FOUND:', {
name: productName,
unitPrice: unitPrice,
quantity: quantity,
subtotal: subtotal
});
items.push({
json: {
From: fromEmail,
Subject: subject,
DateYear: year,
DateMonth: month,
DateDay: day,
Product: productName,
Quantity: quantity,
SubTotal: subtotal
}
});
} else {
console.log('DUPLICATE PRODUCT SKIPPED:', productName);
}
}
// マッチしなかった場合のフォールバック(bullet分割)
if (items.length === 0) {
console.log('No matches found, trying bullet split method');
const bulletChars = ['•', '●', '・'];
let productParts = [];
for (const bullet of bulletChars) {
const parts = productSection.split(bullet).filter(part => part.trim().length > 0);
if (parts.length > 1) {
productParts = parts;
console.log(`Split by "${bullet}":`, productParts.length, 'parts');
break;
}
}
for (let i = 0; i < productParts.length; i++) {
const part = productParts[i].trim();
console.log(`Processing part ${i + 1}:`, part);
// 各パートから商品情報を抽出(重複回避)
const partMatch = part.match(/(.+?)\s+価格\s+¥(\d+(?:,\d{3})*)\s+x\s*(\d+)\s*=\s*¥(\d+(?:,\d{3})*)/);
if (partMatch) {
const productName = partMatch[1].trim();
const unitPrice = parseInt(partMatch[2].replace(/,/g, ''));
const quantity = parseInt(partMatch[3]);
const subtotal = parseInt(partMatch[4].replace(/,/g, ''));
const productKey = `${productName}_${quantity}`;
if (!foundProducts.has(productKey)) {
foundProducts.add(productKey);
items.push({
json: {
From: fromEmail,
Subject: subject,
DateYear: year,
DateMonth: month,
DateDay: day,
Product: productName,
Quantity: quantity,
SubTotal: subtotal
}
});
}
}
}
}
}
// 商品が見つからない場合のフォールバック
if (items.length === 0) {
console.log('NO PRODUCTS FOUND - adding fallback');
items.push({
json: {
From: fromEmail,
Subject: subject,
DateYear: year,
DateMonth: month,
DateDay: day,
Product: 'データ解析エラー',
Quantity: 0,
SubTotal: 0
}
});
}
}
} catch (error) {
console.error('=== ERROR ===', error);
return [{
json: {
From: 'error@system.com',
Subject: 'Processing Error',
DateYear: new Date().getFullYear().toString(),
DateMonth: String(new Date().getMonth() + 1).padStart(2, '0'),
DateDay: String(new Date().getDate()).padStart(2, '0'),
Product: `Error: ${error.message}`,
Quantity: 0,
SubTotal: 0
}
}];
}
console.log('=== FINAL RESULT ===');
console.log('Items count:', items.length);
console.log('Items:', JSON.stringify(items, null, 2));
return items;
3. テストメール
- YouTube 「【n8n自動化】GmailからGoogleスプレッドシートへ自動転記する方法|週5-10時間削減」で使用したテストメール
!