Reputation: 1
I have frankensteined this code a little, and it gets me 95% of what I want, but I can't figure out how to have it pull just a specific date range. Right now it grabs the whole inbox, and I don't need that each time I run it.
Any help would be amazing! Thank you.
function getGmailEmails(query = "Label:Inbox") {
const after = "2024/08/09"; // NEW
const before = "2024/08/12"; // NEW
query += ` after:${after} before:${before}`; // NEW
var threads = GmailApp.getInboxThreads();
for (var i = 0; i < threads.length; i++){
var messages = threads [i].getMessages();
var msgCount = threads[i].getMessageCount();
for (var j = 0; j <messages.length; j++){
message = messages[j];
if (message.isInInbox()) {
extractDetails (message, msgCount);
}
}
}
}
function extractDetails (message, msgCount) {
var spreadSheetId='SS+ID+HERE';
var sheetname = "Sheet1";
var ss = SpreadsheetApp.openById(spreadSheetId);
var timezone = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();
var sheet = ss.getSheetByName (sheetname);
const today = new Date();
var dateTime = Utilities.formatDate(message.getDate(), timezone, "dd-MM-yyyy")
var subjectText = message.getSubject();
var fromSend = message.getFrom();
var toSend = message.getTo();
var bodyContent = message.getPlainBody();
sheet.appendRow( [dateTime, msgCount, fromSend, toSend, subjectText, bodyContent]);
}
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Pull Email Data')
.addItem('Run Email Data Pull','getGmailEmails')
.addToUi();
}
I tried different date formats and locations, but it keeps pulling the full inbox, not the range I'm attempting to pull from.
Upvotes: 0
Views: 63
Reputation: 38416
The date separator should be a hyphen (-
), not a slash (/
).
From
const after = "2024/08/09"; // NEW
const before = "2024/08/12"; // NEW
To
const after = "2024-08-09"; // NEW
const before = "2024-08-12"; // NEW
Please keep in mind that your script searches for threads instead of searching for messages. If your mailbox is set to use the conversation view, you should ensure that your script "filters" each thread the query returns to extract only the messages in the specified date range.
Related
Upvotes: 0