Save attachment from Gmail to Google Drive AND giv

2020-06-29 14:44发布

问题:

I am using Amit Agarwal's fantastic script to extract attachments from Google Mail and save them to Google Drive. It saves the attachment under its name and saves the Subject Line of the mail in the "Description" of the file (together with the Message ID). Instead, I would like to name the file whatever is written in the subject line of the email with the attachment.

An example: The attachment is named abc.pdf, the subject line is "Invoice-February.pdf". As it is, the script would create a file in Google Drive called abc.pdf. Instead, I would like it to name the file "Invoice-February.pdf".

This is the original code:

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

var message = threads[x].getMessages()[0];    
var desc   = message.getSubject() + " #" + message.getId();
var att    = message.getAttachments();

for (var z=0; z<att.length; z++) {
  try {        
    if (check) {
      var name = att[z].getName();
      if (name.indexOf(".") != -1) {
        var extn = name.substr(name.lastIndexOf(".")+1).toLowerCase();
        if (valid.indexOf(extn) != -1) {
          file = folder.createFile(att[z]);
          file.setDescription(desc);
        } else {
          Logger.log("Skipping " + name);
        }
      }
    } else {
      file = folder.createFile(att[z]);
      file.setDescription(desc);
    }  
  }

The createFile function has no way to add a different name to a blog and I have not found a "renameFile". Does anyone know how to do that?

回答1:

I would suggest you take a look at https://github.com/ahochsteger/gmail2gdrive

There is the option to rename attachments under the Config.gs Rules:

// * filenameFrom (String, optional): The attachment filename that should be renamed when stored in Google Drive // * filenameTo (String, optional): The pattern for the new filename of the attachment. You can use '%s' to insert the email subject and date format patterns like 'yyyy' for year, 'MM' for month and 'dd' for day as pattern in the filename.



回答2:

After this line:

      file = folder.createFile(att[z]);

add these lines for renaming the created file.

      var extn = file.getName().split('.').pop();
      file.rename(message.getSubject() + z + "." + extn);

I have added "z" to have unique names in case a message includes multiple attachments.