![](/img/trans.png)
[英]Retrieve csv attachment file from gmail and place the data in a google spreadsheet
[英]Retrieve a CSV file received over Gmail from a specific email address to a specific Google Sheet
問題的目標:
已經嘗試過: 將通過 Gmail 從特定電子郵件 ID 接收的 CSV 文件自動化到特定的 Google 表格
但沒有什么能具體解決上述三個問題。
function myFunction() {
const messageId = "###"; // Please set the message ID of Gmail.
const sheetName = "Sheet1"; // Please set the sheet name you want to put the values.
const delimiter = ","; // If your CSV data uses the specific delimiter, please set this.
const skipRows = 2; // 2 is from your question.
// 1. Retrieve message.
const message = GmailApp.getMessageById(messageId);
// 2. Retrieve attachment files.
const attachments = message.getAttachments();
if (attachments.length == 0) {
console.log("No attachment files.");
return;
}
// 3. Create an array for putting to Spreadsheet from the CSV data of attachment files.
const values = attachments.reduce((ar, e) => {
if (e.getContentType() == MimeType.CSV || e.getName().includes(".csv")) {
ar = [...ar, ...Utilities.parseCsv(e.getDataAsString(), delimiter).splice(skipRows)];
}
return ar;
}, []);
if (values.length == 0) {
console.log("No values.");
return;
}
// 4. Put the values to Spreadsheet.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); // and, you can also use. const sheet = SpreadsheetApp.openById("###spreadsheetId###").getSheetByName(sheetName);
sheet.getRange(sheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
}
嘗試了上面的代碼,但它顯示錯誤異常:無效參數:在 myFunction(代碼:8:28)
僅供參考,我也想使用工作表 ID 而不是工作表名稱
嘗試(輸入電子表格 ID、主題 - 如果您有多個單詞,請在后面的示例中指定 - 以及發件人的電子郵件):
const getGmailAttachment = () => {
const ssID = '############'
const searchQuery = 'from:######@gmail.com in:inbox has:attachment subject:##### subject:###';
const threads = GmailApp.search(searchQuery, 0, 1);
threads.forEach(thread => {
const message = thread.getMessages()[Number(thread.getMessageCount() - 1)];
const attachments = message.getAttachments();
attachments.forEach((attachment, i) => {
if (i == 0) {
console.log(attachment.getName())
const sheet = SpreadsheetApp.openById(ssID).getSheets()[0];
sheet.getDataRange().clearContent()
const csvData = Utilities.parseCsv(attachment.getDataAsString()).splice(2); // except 2 first rows
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
});
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.