user2958378
user2958378

Reputation: 1

Google Apps script Save to Drive

I am by no means a programmer but I was able to put a script together that looks for an email with attachment, finds, saves the attachment to Google Drive and logs subject line into a spreadsheet. Here is a part that does that:

function sendToGDrive() {    

var sheet   = SpreadsheetApp.getActiveSheet();
var gLabel  = sheet.getRange("G1:G1").getValues();
var gFolder = sheet.getRange("H1:H1").getValues();
var row = SpreadsheetApp.getActiveSpreadsheet().getLastRow() + 1;

var threads = GmailApp.search("label:" + gLabel, 0, 5);  
var folder  = DocsList.getFolder(gFolder);

for (var x=0; x<threads.length; x++) {

var messages = threads[x].getMessages();

for (var y=0; y<messages.length; y++) {

var att = messages[y].getAttachments();

 for (var z=0; z<att.length; z++) {
    try {
      var file = folder.createFile(att[z]);
      sheet.getRange(row,1).setValue(Utilities.formatDate(messages[y].getDate(), "PST",        "yyyy-MM-dd"));
      sheet.getRange(row,2).setValue(messages[y].getSubject());                                      
      var id = "https://mail.google.com/mail/?shva=1#all/" + messages[y].getId();
      sheet.getRange(row,3).setFormula('=hyperlink("' + id + '", "View email")');
      var url = file.getUrl();
      sheet.getRange(row,4).setFormula('=hyperlink("' + url + '", "View image")');
      sheet.getRange(row,5).setValue(file.getName());
      row++;
      Utilities.sleep(1000);
    }

What I can't figure out is how to extend this script to also look for emails without attachment as well and do all of the above. I would think that it would require if/or statement, I just can't figure out how to make it work. Please help.

Upvotes: 0

Views: 1549

Answers (1)

eddyparkinson
eddyparkinson

Reputation: 3700

After:

var att = messages[y].getAttachments();

you want something like

if(att.length==0) {
   // no attachments code
} else {
   // attachments code
   for (var z=0; z<att.length; z++) {
   ......

}

Eddy - Spreadsheet forumlas that build web applications

Upvotes: 1

Related Questions