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`
Related
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 am new to Google AppScripts, and really struggling with achieving my end goal. The following code get's me very close, but I am wondering if anyone can please point me in a direction that enables me to do the following:
Extract .xlsx file from gmail that is received daily
Transfer the contents of the .xlsx file to an already existing Google sheet
Any advice would be hugely appreciated.
James
// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['jpg', 'tif', 'png', 'gif', 'bmp', 'svg'];
//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: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 ' + 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();
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;
}
That's the codes I'm using for getting attachments from gmail to existing spreadsheet.
By setting up time driven trigger.
In order to make this function run faster. set the label name and the thread limites
function attachfromGmail(attachmentname, destsheet_id, destsheetname, label_name, all_or_part) {
const folder = DriveApp.getFolderById("xasdawfes2342ke");
const labels = GmailApp.getUserLabelByName(label_name).getThreads(0, 10);
const threads = GmailApp.getMessagesForThreads(labels);
const today_date = Utilities.formatDate(new Date(), "GMT-6", "MM/dd/yyyy");
var fileid_FromGmail = "";
threads.forEach(threads => {
threads.filter(messge => {
if (Utilities.formatDate(messge.getDate(), "GMT-6", "MM/dd/yyyy") == today_date) {
messge.getAttachments().filter(attachments => {
if (attachments.getName() == attachmentname && messge.isUnread() === true) {
messge.markRead();
const blob = attachments.copyBlob();
var file_FromGmail = Drive.Files.insert(
{ title: attachmentname, parents: [{ "id": folder.getId() }] },
blob,
{ convert: true }
);
fileid_FromGmail = file_FromGmail.id;
}
})
}
})
})
const created_file = SpreadsheetApp.openById(fileid_FromGmail);
const values = created_file.getDataRange().getDisplayValues();
const destfiles_sheet = SpreadsheetApp.openById(destsheet_id).getSheetByName(destsheetname);
if (all_or_part === 'all' && values != undefined) {
destfiles_sheet.clear();
destfiles_sheet.getRange(1, 1, created_file.getLastRow(), created_file.getLastColumn()).setValues(values);
} else if (values.length === 1 && values.toString() != 'No Data Available' || values.length > 1) {
values.shift()
destfiles_sheet.getRange(destfiles_sheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
}
//delete created file
DriveApp.getFileById(fileid_FromGmail).setTrashed(true);
}
It works well, but I'm trying to get a better way to do the job. Instead of insert a new file and delete. I know we can use csv parse function to get the data. but I can not fix the leading 0 issue in the csv file.
Then I'm trying to use XML file to transfer data, still working on it.
I will update this post if I get a better solution.
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.
I have a functioning script that grabs all CSV attachments in Gmail, and puts them into a folder on Google Drive. It then removes the old file.
This is required because I have scheduled reports emailed to me every day. The old CSVs must be removed.
Now I need to convert the CSV file to Google Spreadsheet, without creating multiple files of the same name.
I used the Drive API to copy the file with the parameter {convert: true}. This will just create a duplicate spreadsheet every time, which I don't want. I have removed this code. Here is the functioning script that just moves the CSV file and deletes the old CSV file:
// GLOBALS
//Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['csv'];
//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: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 ' + 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();
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 AttachmentTitle = attachment.getName();
var attachmentBlob = attachment.copyBlob();
var existingFile = DriveApp.getFilesByName(attachment.getName());
if (existingFile.hasNext()) {
var file = existingFile.next();
file.setTrashed(true);
}
var filetemp = 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;
}
Instead of trying to save the CSV on the drive and convert it into a Google Spreadsheet, you can
directly import the CSV from the attachment into a spreadsheet created for this purpose
Sample
var ss=SpreadsheetApp.create(attachment.getName());
var sheet=ss.getActiveSheet();
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
var file=DriveApp.getFileById(ss.getId())
parentFolder.addFile(file);
root.removeFile(file);
Full code:
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:'+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();
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 AttachmentTitle = attachment.getName();
var files = DriveApp.getFilesByName(AttachmentTitle);
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
file.setTrashed(true);
}
var ss=SpreadsheetApp.create(attachment.getName());
var sheet=ss.getActiveSheet();
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
var file=DriveApp.getFileById(ss.getId())
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;
}
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();
}
}