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;
}
CodePudding user response:
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)