I'm trying to get the latest attachment of the latest message of a thread in gmail through google apps script. Here is what I have:
//gets first(latest) message with set label
var label = GmailApp.getUserLabelByName('SpecificLabel');
var threads = label.getThreads();
var message = threads[0].getMessages();
//message.reverse
var attachment = message[threads[0].getMessageCount()-1].getAttachments()[0];
var ss = SpreadsheetApp.getActive();
var summarySht = ss.getSheetByName('Summary');
var dbPullSht = ss.getSheetByName('Database Pull');
Browser.msgBox(attachment.getContentType());
// Is the attachment a CSV file
if (attachment.getContentType() === 'text/csv') {
//do something
}
I've tried to reverse the message with the code I commented out. That didn't seem to work. Currently the message box will state that the attachment is an image. I think it's accessing the correct message of the correct thread but it is pulling an image the sender has in their signature.
This is how it works. I send an xls file to someone. They send back a CSV file. I need that CSV file.
I have created a for-loop to get the attachment with the correct name. This assumes that the file name will be the same.
//gets first(latest) message with set label
var label = GmailApp.getUserLabelByName('SpecificLabel');
var threads = label.getThreads(0, 1);
var message = threads[0].getMessages();
message = message[message.length - 1];
var attachments = message.getAttachments();
for (var i = 0; i < attachments.length; i++) {
if (attachments[i].getName() === 'filename.csv') {
var attachment = attachments[i];
}
}
var ss = SpreadsheetApp.getActive();
var summarySht = ss.getSheetByName('Summary');
var dbPullSht = ss.getSheetByName('Database Pull');
Browser.msgBox(attachment.getContentType());
Browser.msgBox(attachment.getName());
// Does the attachment name match?
if (attachment.getName() === 'filename.csv') {
//do something
}
This will also do a check for the name of the file instead of the filetype before continuing with the code.