I need saving the attachments im mails from one sender with file format 'gz' to folder GmailToDrive in Google-drive with replacement old file
Here Apps script saving attachments from last mail I get answer with script, but something is wrong.
I think, this - query = 'in:inbox has:nouserlabels ' + query + ' AND from:entrepot#fmlogistic.fr AND older_than:4h';
Can you help me? thank you very much!
// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['gz'];
//Name of the folder in google drive i which files will be put
var folderName = 'GmailToDrive';
//Name of the label which will be applied after processing the mail message
var labelName = 'GmailToDrive';
function GmailToDrive(){
var query = '';
//filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+formattedDate+
for(var i in fileTypesToExtract){
query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
}
//ADD the only email adress you want to check + EDIT : only last 24h emails
query = 'in:inbox has:nouserlabels ' + query + ' AND from:entrepot#fmlogistic.fr AND older_than:4h';
var threads = GmailApp.search(query);
var label = getGmailLabel_(labelName);
var parentFolder;
if(threads.length > 0){
parentFolder = getFolder_(folderName);
}
var root = DriveApp.getRootFolder();
for(var i in threads){
var mesgs = threads[i].getMessages();
for(var j in mesgs){
//ADD: check if the mail is unread:
if (mesgs[j].isUnread()) {
var attachments = mesgs[j].getAttachments();
for(var k in attachments){
var attachment = attachments[k];
var isDefinedType = checkIfDefinedType_(attachment);
if(!isDefinedType) continue;
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
parentFolder.addFile(file);
root.removeFile(file);
}
}
} // close if unread
} // close for msg loop
//ADD: Set thread (all mail included) as read
GmailApp.markThreadRead(threads[i]);
threads[i].addLabel(label);
}
As per documentation:
older_than can be used for messages older than a time period using d (day), m (month), and y (year)
So, 4h won't work.
Related
Trying to get all unread emails and save the pdf attachments to google drive. When looping through the threads I get an error saying getFrom is undefined. It used to work but doesn't anymore it gets to the first unread email and spits out the error.
var fileTypesToExtract = ['pdf'];
//Name of the label which will be applied after processing the mail message
var labelName = 'SaveToDrive';
function GmailToDrive(){
//build query to search emails find if email doesnt have savetodrive label for duplicates
var query = '';
//GmailApp.getUserLabelByName('receipts-new')
//filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+getDateNDaysBack_(1)+
for(var i in fileTypesToExtract){
query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
}
query = 'is:unread ' + query;
var threads = GmailApp.search(query);
console.log(threads);
var label = getGmailLabel_(labelName);
var parentFolder;
var root = DriveApp.getRootFolder();
if(threads == null){
exit;
}
for(var i in threads){
var mesgs = threads[i].getMessages;
console.log(mesgs);
// console.log(threads[i]);
>! if(mesgs[i] == undefined){
>! console.log("Email Undefined");
>! continue;
>! }
var senderAddress = mesgs[i].getFrom();
var emailSubject = mesgs[i].getSubject();
console.log("Subject: "+emailSubject);
console.log("Sender Address: "+senderAddress);
folderPicker_(emailSubject, senderAddress);
if(threads.length > 0){
parentFolder = getFolder_(folderName);
}
//get attachments
var attachments = mesgs[i].getAttachments();
for(var k in attachments){
var attachment = attachments[k];
var isDefinedType = checkIfDefinedType_(attachment);
if(!isDefinedType) continue;
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
parentFolder.addFile(file);
root.removeFile(file);
}
threads[i].addLabel(label);
threads[i].markRead();
console.log("Sucessfull save to drive and label added");
}
}
Error
TypeError: Cannot read property 'getFrom' of undefined
GmailToDrive # Code.gs:40`
To download several PDF files from gmail I'm using the following script. It works fine, there is just a detail I need to change. I need the name of the downloaded PDF-File to be name of the subject title of the mail. If tried to modify it, but it doesn't work :/ Any hints which line I have to change to get the desired output?
function GmailToDrive(){
//build query to search emails
var query = '';
//filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+getDateNDaysBack_(1)+
for(var i in fileTypesToExtract){
query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
}
query = 'label:inbox-Gesellschafter is:unread ' + query;
// query += ' after:'+getDateNDaysBack_(1);
var threads = GmailApp.search(query);
var label = getGmailLabel_(labelName);
var parentFolder;
if(threads.length > 0){
parentFolder = getFolder_(folderName);
}
var root = DriveApp.getRootFolder();
for(var i in threads){
var mesgs = threads[i].getMessages();
for(var j in mesgs){
//get attachments
var attachments = mesgs[j].getAttachments();
for(var k in attachments){
var attachment = attachments[k];
// var isDefinedType = checkIfDefinedType_(attachment);
// if(!isDefinedType) continue;
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
parentFolder.addFile(file);
root.removeFile(file);
}
}
threads[i].addLabel(label);
}
}
//This function will get the parent folder in Google drive
function getFolder_(folderName){
var folder;
var fi = DriveApp.getFoldersByName(folderName);
if(fi.hasNext()){
folder = fi.next();
}
else{
folder = DriveApp.createFolder(folderName);
}
return folder;
}
//getDate n days back
// n must be integer
function getDateNDaysBack_(n){
n = parseInt(n);
var date = new Date();
date.setDate(date.getDate() - n);
return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy/MM/dd');
}
function getGmailLabel_(name){
var label = GmailApp.getUserLabelByName(name);
if(!label){
label = GmailApp.createLabel(name);
}
return label;
}
//this function will check for filextension type.
// and return boolean
function checkIfDefinedType_(attachment){
var fileName = attachment.getName();
var temp = fileName.split('.');
var fileExtension = temp[temp.length-1].toLowerCase();
if(fileTypesToExtract.indexOf(fileExtension) !== -1) return true;
else return false;
}
Sure, just modify the existing code by getting the subject and then using it in your existing code.
var attachments = mesgs[j].getAttachments();
// now also get the subject
var subject = mesgs[j].getSubject()
// now use the subject
var file = DriveApp.createFile(attachmentBlob).setName(subject)
I have a function that successfully extracts file attachments from new emails. But it is unable to detect hyperlinked attachments like this email from our office scanner:
Would anyone know of an approach to address this?
UPDATE:
I found a similar case in How to download file from a download link on Gmail and uploading it to Google Drive using Google Apps Script
and revised my code below.
Here's the result:
a) extracting a hyperlinked attachment using this publicly available URL (people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv) as my sample attachment works OK and saves it in my preferred filename, but
b) for the actual email from our scanner I get this error message when it executes UrlFetchApp.fetch(url):
Exception: Bad request: http://10.87.38.21:8000/cmj/asd/download?dev=...
What could be causing this issue?
(my revised code below):
//===================================
function ExtractEmailAttachmentsJP() {
//===================================
var spr = SpreadsheetApp.getActiveSpreadsheet();
var ss = SpreadsheetApp.getActiveSheet();
var sheet = SS.getSheetByName("UPLOADER");
var logsheet = SS.getSheetByName("Documents Uploaded");
TEMPFOLDERID = PropertiesService.getDocumentProperties().getProperty('TEMPFOLDERID');
TEMPFOLDER = DriveApp.getFolderById(TEMPFOLDERID);
//do not overwrite, just append to the last non-empty (max) row
var startRow = lastNonblankRow("N",SSID,"UPLOADER")+1
COUNTER = 0; //initialize file attachment counter
var gmailLabels = "PeopleDoc";
var threads = GmailApp.search("label:" + gmailLabels + " is:Unread", 0, 3);
if (threads.length > 0) {
SS.toast("New emails found. Extracting attachment(s)...");
/*Iterate through the threads of emails*/
for (var t=0; t<threads.length; t++) {
var msgs = threads[t].getMessages();
//Iterate through each mail
for (var m=0; m<msgs.length; m++) {
var msg = msgs[m];
var data = msg.getPlainBody();
var urlField = data.indexOf('http://');
var url = data.substr(urlField, 117);
var fileUrl = UrlFetchApp.fetch(url);
var fileBlob = fileUrl.getBlob();
COUNTER = COUNTER + 1;
var timestamp = Utilities.formatDate(new Date(msg.getDate()), "GMT+8", 'dd MMM hh:mm');
var pdfID = TEMPFOLDER.createFile(fileBlob).setName("attachment" + COUNTER + " " + timestamp).getId();
//show each generic file row by row
sheet.getRange(startRow-1+COUNTER, 10).setFormula('=HYPERLINK(\"https://drive.google.com/file/d/' + pdfID + '\", \"' + "attachment" + COUNTER + " " + timestamp + '\")');
sheet.getRange(startRow-1+COUNTER, 15).setValue(pdfID);
sheet.getRange(startRow-1+COUNTER, 16).setValue("Gmail Inbox");
}
I copied some codes to move Gmail attachments to Google Drive, add a label to the mail, then trash or archive the mail (I have tried both trash and archive but results are the same):
The incoming mails are from the same sender (a machine) with the same subject every time.
The email arrives at random timing, could be several mails in a minute or nothing in few hours.
The filenames has the suffix in yyyy-mm-dd-hh-mm-ss format.
The problem I am facing is when the script processes the new emails in the inbox, it also processes those in the trash. This results duplication of older files. Same problem happens even if I change moveToTrash() to moveToArchive().
How can I prevent my script from duplicating older files (from previously processed emails)?
function GmailToDrive(){
//build query to search emails
var query = '';
//filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:jpeg'; //'after:'+formattedDate+
for(var i in fileTypesToExtract){
query += (query === '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
}
query = 'in:inbox has:nouserlabels ' + query;
var threads = GmailApp.search(query);
var label = getGmailLabel_(labelName);
var parentFolder;
if(threads.length > 0){
parentFolder = getFolder_(folderName);
}
var root = DriveApp.getRootFolder();
for(var i in threads){
var mesgs = threads[i].getMessages();
mesgs.reverse();
for(var j in mesgs){
//get attachments
var attachments = mesgs[j].getAttachments();
for(var k in attachments){
var attachment = attachments[k];
var isDefinedType = checkIfDefinedType_(attachment);
if(!isDefinedType) continue;
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
parentFolder.addFile(file);
root.removeFile(file);
}
}
threads[i].addLabel(label);
threads[i].moveToTrash();
threads[i].refresh();
}
}
I have found the following script in this forum and works really smoothly (takes files, saves files in the right folder, etc.). Namely I receive a txt. file every morning with relative quantities which I would like to import and save to my Gdrive (to later use in other scripts). The file is named with todays date which I have used the Utilities.formatDate function to obtain.
Unfortunately every time I run the script I get all files from even from previous days which would spam my folder full in a couple of days. Therefore my question is whether one can delete the emails after the script that my google search query will not find the previous emails the following day?
Any help with this conundrum appreciated!!
P.S: Email comes from the same recipient, with an identical subject "Stock_Load", however the attachment is named "date"_Todays Date.
// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['txt'];
//Name of the folder in google drive i which files will be put
var folderName = 'GmailToDrive';
//Name of the label which will be applied after processing the mail message
var labelName = 'GmailToDrive';
function GmailToDrive(){
//build query to search emails
var query = 'filename:stock_'+Utilities.formatDate(new Date(), "GMT", "yyyyMMdd").toString()+'.gpg.txt';
//filename:jpg OR filename:tif OR filename:gif OR fileName:png OR filename:bmp OR filename:svg'; //'after:'+formattedDate+
for(var i in fileTypesToExtract){
query += (query == '' ?('filename:'+fileTypesToExtract[i]) : (' OR filename:'+fileTypesToExtract[i]));
}
query = 'in:inbox has:nouserlabels is:unread' + query;
var threads = GmailApp.search(query);
var label = getGmailLabel_(labelName);
var Folder = DriveApp.getFolderById("XXX");
for(var i in threads){
var mesgs = threads[i].getMessages();
for(var j in mesgs){
//get attachments
var attachments = mesgs[j].getAttachments();
for(var k in attachments){
var attachment = attachments[k];
var isImageType = checkIfImage_(attachment);
if(!isImageType) continue;
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
Folder.addFile(file);
}
}
threads[i].addLabel(label);
}
};
//This function will get the parent folder in Google drive
function getFolder_(folderName){
var folder;
try {folder = DriveApp.getFolder(folderName)}
catch(e){ folder = DriveApp.createFolder(folderName);}
return folder;
}
//getDate n days back
// n must be integer
function getDateNDaysBack_(n){
n = parseInt(n);
var today = new Date();
var dateNDaysBack = new Date(today.valueOf() - n*24*60*60*1000);
return dateNDaysBack;
}
function getGmailLabel_(name){
var label = GmailApp.getUserLabelByName(name);
if(label == null){
label = GmailApp.createLabel(name);
}
return label;
}
//this function will check for filextension type.
// and return boolean
function checkIfImage_(attachment){
var fileName = attachment.getName();
var temp = fileName.split('.');
var fileExtension = temp[temp.length-1].toLowerCase();
if(fileTypesToExtract.indexOf(fileExtension) != -1) return true;
else return false;
}