Coder Social home page Coder Social logo

ahochsteger / gmail-processor Goto Github PK

View Code? Open in Web Editor NEW
462.0 27.0 133.0 17.07 MB

Gmail Processor is an open-source project that automates the processing of Gmail messages and attachments using Google Apps Script and execute actions (e.g. store attachments in a GDrive folder, log information in a spreadsheet) depending on matching criteria.

Home Page: http://ahochsteger.github.io/gmail-processor/

License: Apache License 2.0

JavaScript 11.05% Shell 3.58% TypeScript 83.07% jq 1.69% HTML 0.53% Dockerfile 0.08%
automation gmail script

gmail-processor's Introduction

๐Ÿ“ง Gmail Processor ๐Ÿค– - Automate Email Processing with Ease

GitHub GitHub release (with filter) GitHub Release Date - Published_At GitHub Workflow Status (with event) Coveralls branch

More badges ...

GitHub tag (with filter) GitHub Repo stars GitHub forks GitHub all releases

GitHub commit activity (branch) GitHub repo size GitHub contributors All Contributors Contributor Covenant

GitHub issues GitHub closed issues GitHub pull requests GitHub closed pull requests Known Vulnerabilities

Lines of Code Maintainability Rating Bugs Code Smells Security Rating Vulnerabilities Duplicated Lines (%)

Gmail Processor is an open-source Google Apps Script library that automates the processing of Gmail messages and attachments by executing actions (e.g. store attachments in a GDrive folder, log information into a spreadsheet) depending on powerful matching criteria.

Dall-e generated image: A friendly smiling robot sitting on a table, sorting mails into three paper trays, colorful flat style, white background

Gmail Processor is the successor of Gmail2GDrive with vastly enhanced functionality, completely re-written in TypeScript with extensibility and stability in mind, using a modern development setup and automation all over the place (dependency updates, tests, documentation, releases, deployments). There's a convenient migration available to convert your old configuration to the new format (see Migrating from GMail2GDrive).

Key Features

  • ๐Ÿค– Extensive Automation: Automate email processing using the provided configuration to match threads, messages, and attachments, and trigger actions accordingly.
  • ๐Ÿ“ Google Drive Integration: Store files such as attachments, PDFs of messages, or entire threads into any location within Google Drive, providing easy organization and accessibility.
  • โœ‚๏ธ OCR Text Extraction: Extract text (e.g. invoice number) from attached documents (JPEG, PNG, GIF, PDF) to organize and annotate your attachments.
  • ๐Ÿ“„ Google Spreadsheet Logging: Keep track of processed threads, messages, and attachments by logging valuable information into a Google Spreadsheet.
  • ๐Ÿ”ง Flexible Configuration: Gmail Processor operates based on a JSON configuration that allows you to define matching rules and specify corresponding actions to be executed.
  • ๐Ÿ“ Extensible Architecture: Designed with extensibility in mind, Gmail Processor enables seamless addition of new actions and integrations in the future to adapt to evolving requirements.

Getting Started

The Getting Started Guide shows how to setup Gmail Processor in Google Apps Script and quickly get it up and running.

Config Reference

The Config Reference provides detailed information about the Gmail Processor configuration.

Examples

The Examples show different ways of using Gmail Processor.

Playground

The Playground helps to create the configuration in a schema-aware online editor with a visual schema guide on the side.

Contributing

Contributions to Gmail Processor are welcome! Whether you want to add new features, fix bugs, or improve documentation, check out the contribution guidelines to get started.

Development Guide

See the Development Guide for details.

Contributors

Andreas Hochsteger
Andreas Hochsteger

๐Ÿ’ป ๐Ÿ“– ๐Ÿ’ก ๐Ÿš‡ ๐Ÿšง ๐Ÿ‘€ ๐Ÿ”ง โš ๏ธ
Piraveen Kamalathas
Piraveen Kamalathas

๐Ÿ’ป ๐Ÿ“–
Ciprian Constantinescu
Ciprian Constantinescu

๐Ÿ’ป ๐Ÿ’ก
marcusschweizer
marcusschweizer

๐Ÿ’ป
Markus Kurzmann
Markus Kurzmann

๐Ÿ’ป
NadavClaudeCohen
NadavClaudeCohen

๐Ÿ’ป ๐Ÿ“– ๐Ÿ’ก
Schuller Tom
Schuller Tom

๐Ÿ’ป ๐Ÿ’ก
Tom Judge
Tom Judge

๐Ÿ’ป ๐Ÿ’ก
David Lemayian โœจ
David Lemayian โœจ

๐Ÿ“–
Denny de la Haye
Denny de la Haye

๐Ÿ’ป
steve192
steve192

๐Ÿ’ป
gregory nicholas
gregory nicholas

๐Ÿ’ก
Gabriel Esposito
Gabriel Esposito

๐Ÿ“–
Add your contributions

License

GmailProcessor is released under the Apache 2.0 License.

Support

For any questions, issues, or feedback, please open an issue on GitHub.

gmail-processor's People

Contributors

ahochsteger avatar amishhammer avatar cciprian5 avatar claude123 avatar davidlemayian avatar denny avatar dependabot[bot] avatar gregorynicholas avatar maks-io avatar marcusschweizer avatar piraveen avatar renovate[bot] avatar semantic-release-bot avatar steve192 avatar tomlux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gmail-processor's Issues

Shared Drive

Hello!

Is there a way to specify a Shared Drive (instead of "My Drive") as the folder base?

Thanks!

Attachments not moving but no processing errors

I am using a gdrive to create subfolders for our team to easily find their files. I set up a filter to sort the email by subject and send it to the appropriate subfolder. Each team member has a specific subject line to use. The script runs without any error codes but the files do not move. I suspect I am setting up the rules incorrectly. Here is the filter I am using:

{ // Sunday HS Boys
"filter": "subject:Sunday HS Boys",
"folder": "'Small Groups/Sunday/HS Boys'"
},

There are multiple rules following the same structure.

Function Not Working

H Experts, I am new to Google Apps script and was trying out the script with customization based on the links provided in readme file. When I tried to test the function, it completed immediately, but did not work and Execution log is empty.

No Files Saved and label

9:19:05 AM Notice Execution started
9:19:05 AM Notice Execution completed

Am I doing something wrong ?

function getgmail2GDriveConfig() {
return {
// Global filter
"globalFilter": "has:attachment -in:trash -in:drafts -in:spam",
// gmail label for processed threads (will be created, if not existing):
"processedLabel": "to-gdrive/processed",
// Sleep time in milli seconds between processed messages:
"sleepTime": 100,
// Maximum script runtime in seconds (google scripts will be killed after 5 minutes):
"maxRuntime": 280,
// Only process message newer than (leave empty for no restriction; use d, m and y for day, month and year):
// example "newerThan": "2m"
"newerThan": "2m",
// Timezone for date/time operations:
"timezone": "GMT",
// Processing rules:
"rules": [
{
// Bills - To save all PDF attachments in mails labelled Statusupdate to folder in googledrive - emailattach/Statusupdate
"filter": "label:Statusupdate",
"folder": "'emailattach/Statusupdate'",
"filenameFromRegexp": ".*.pdf$",
"filenameTo": "yyyy-MM-dd-'%o-%d.txt'"
},
]
};
}

How to only add date ("YYYY-MM-DD_") as a file name prefix to the original attachment's file name

Hello,

First of all thanks for the great script! It works like a charm.

I'd like to rename attachments by simply adding a processing date prefix ('YYYY-MM-DD_') ; this prefix should only come as an addition to the original name and extension of the attachment which should both be preserved.
eg:
original attachment name example : "originalname.pdf"
desired attachment new name: "YYYY-MM-DD_originalname.pdf'"

How can this be achieved?

Thanks a lot in advance for your help.

Getting error while saving the file to drive folder.

Hi, I configured the script and it is finding and applying the labels perfectly but when it tried to save the file to drive folder it is throwing an error

"Exception: Unexpected error while getting the method or property getRootFolder on object DriveApp."

I tried adding an existing folder or a new folder.

Nothing works. Please help.

Overwrite Existing File

If the file already exists in the GDrive Path how can we have it overwrite instead of creating a duplicate filename?

Weird issue when using get.from or a header parser to get the name of an email sender.

Hello! First of all, I want to thank the author of the script for his work - this is a very useful and necessary project, for example, it helps me automate the collection and sorting of students' homework.

Now the problem: I need to convert downloaded attachment names to sender names (ideally First and last name, no email address). When processing names with Cyrillic characters through getting from, there are no problems - the files are saved under the desired name, however, if the name and surname of the sender are written in Latin, I get the error "Exception: Invalid argument: John Doe". I've tried getting names through getting from and through the header parser.
Parser:

function parseEmailHeader(message) {
  var header = message.getFrom().trim();

  var extract = { name: '', email: '' };

  var emails = header.match(/[^@<\s]+@[^@\s>]+/g);

  if (emails) {
    extract.email = emails[0];
  }

  var names = header.split(/\s+/);

  if (names.length > 1) {
    names.pop();
    extract.name = names.join(' ').replace(/"/g, '');
  }

  return extract;

And the function call:

var sender = parseEmailHeader(message);
      var new_filename = rule.filenameTo.replace('%s',message.getSubject()).replace("%d", String(rule_counter++)).replace('%o', original_attachment_name).replace('%f', sender.name.replace(" ", "_"))

If there is a better solution, I'd be happy to know. Now, unfortunately, it was not possible to achieve the correct processing of names.

Saving Thread as PDF, in Addition to Attachments in the Same Folder

Hello,

I believe there is an issue when attempting to convert the thread to a pdf and save it into the same folder as the attachments when they are stripped.

Here is my rule:

 {
    // Saves Attachments.
    "filter": "has:attachment",
    "saveThreadPDF": true,
    "folder": "'Testing/REQ-'yyyy-MM-dd-HH:mm:ss",
    "filenameTo": "'REQ-'yyyy-MM-dd'-T-'HH:mm:ss'-%s'",
    "archive": true
  }   

When this is executed it actually creates two folders, one for the attachments and one for the email that is converted to pdf.

The attachments go to a new folder such as: Testing/REQ-2020-04-01-08:28:32
On the other hand, the converted pdf goes to a new(different) folder: 'Testing/REQ-'yyyy-MM-dd-HH:mm:ss . In addition, there is two copies of the email in the folder with the subject as the filename.

The goal would be to store everything in the same folder that is created.

User Rate Limit Reached

I'm getting a user/rate limited reached. I believe its because I have an email with attachment that shows up in the inbox every hour, then the script is run every 30 minutes. Looking at the log, it processes all the messages in the thread instead of just the most recent one. So if its hour 12 of the day, it is going to process the last 12 attachments. Is there any way to make it only process the last message and not all the messages in the thread?

Thanks.

Not all rules are processed

Scenario:
Send an email messagr containing an image with a different filetype compared to the filetype being defined in the first rule for this sender in the config section of the script.

Symptom:
In case of multiple rules for one email sender, and the first rule causes a mismatch, the script only interpretes the first rule (resulting log entry: "INFO: Rejecting file 'aaa.png not matching.*.jpg$"). The subsequent rules (in this example the one for the .png filetype) are ignored. Loop terminated. Why?

I'm not able to correct the code myself. Could anyone review/update the coding?

Thanks in advance!

Attachments Processed Multiple Times

Can anyone explain why this script pulls attachments from emails that have already been processed?

It is correctly saving attachments according to my filters, but also saves attachments from emails that match my subject filter that have been trashed in Gmail even when I have removed the label from these emails.

Filter does not work properly (several emails with same subject)

Scenario :
I receive in the same mailbox, everyday, sales reports for several locations (1 email per location)
Email subject is always the same
I created aliases to be able to filter the mails

Symptoms :
The filters are not considered properly, all messages with the same subject name are processed

Example :
I have in my inbox 3 emails with sales report :

I have for testing purpose only one rule for which the filter is
"filter": "to:[email protected]"

But when I execute the program, the 3 emails are processed

I guess this could be because all emails have the same subject?
I tried to apply different labels (before processing gmail2gdrive) but still the same issue.

Any idea how I could fix this?

Thanks
Thomas

Case sensitive file extension for attachments

First, thank you for the great script - it works beautifully.

I tried editing the rules for file extension so that it's not case sensitive e.g. it accepts both .pdf and .PDF

"filenameFromRegexp": "..pdf$" to "filenameFromRegexp": ".(?i).pdf$"

and I am getting the following error in the execution log:
SyntaxError: Invalid regular expression: /.*(?i).pdf$/: Invalid group

For the life of me I can't figure out what's the correct syntax, anyone with better regex skills? Thanks

Replacement of characters in the file name

Hello,
Thanks for the great script.
It works really well.
I would like to exchange letters for the filename that is saved.

I use this script for the filenames:

        "filter": "has:attachment from:[email protected]",
        "folder": "XYZ/XYZ",
        "filenameFromRegexp": ".*\.pdf$"

However, the character "/" is often used in the filename of the attachment. e.g. "timeline/postbox3226.pdf"
How can I replace this with e.g. "-"
Does that work with the replace command? If so, how do I have to use this?

many thanks for your help

Exclude files via regex

I can not figure out how to add the regex ^(?!.AGB).$ to a rule in order to exclude all files containing "AGB" in the filename.
I tried "filenameFromRegexp": "((?!.*AGB).*$)(.*\.pdf$|.*\.PDF$)" but that did not work. Any ideas?

Not working anymore...

Not sure if this is due to a recent Google Script API change or something, but I'm facing this issue where the script is saving attachments from already processed emails into my Google Drive.

For example, here's an email that has just come through. I should only expect 1 new attachment in my Google Drive:

image

However, I'm getting multiple attachments:

image

I haven't touched the script ever since I set it up and got it working. I've updated the script to match the latest one on your Github, but I'm still facing the same issue. My config is all good, labels are being applied correctly.

The thing is, if all emails are processed and have the "to-gdrive/processed" label assigned, then the script won't create new attachments. So it seems that only when new emails arrive, it will go through all previously processed emails. But when no new emails arrive, all previously processed emails will be ignored (which is correct, as this is the correct behaviour).

DocList Depreciated

Tried updating to DriveApp but has further issues with files and folders.

It either creates a entirely new folder each time it runs or shows type error "TypeError: Cannot find function createFile in object folderAbc"

please help.

Date format patterns for folder

Would you consider adding the possibility to use date format patterns for folders as well? This would be very useful if one is saving attachments in a folder system reflecting the year or month the attachments were received.

save files to shared drive

Hello!

thanks a lot for the nice work!

In my organization we use Google services and we use Shared Drives. I was wondering if there is the possibility to save the files (e.g. attachments) in a folder in a Shared Drive instead of a folder in MyDrive ?

I guess some modification would be needed in function getFolderByPath(path) where by default it starts from the root.

Do you have any suggestions?

What is the use for sleepTime

Nice script, thank you for sharing it, however I'm wondering why is there a 100ms sleep at the end of each iteration ? Is it somehow required for the script to work ?

Two files for different folders

I receive several files in one email.
I want to move each file to another folder in Google Drive.

I tried so and it does not work:
{ // example"
"filter": "has:attachment from:[email protected]โ€",
"folder": "'example1'",
"filenameFromRegexp": "example1..pdf$",
"folder": "'example2'",
"filenameFromRegexp": "example2.
.pdf$"
},

I would appreciate their help

Downloaded files/folders appendix added to google sheet rows

Would be great to have a the feature where a new row is added to a google sheet google sheet populated by data from the created folders or files. that way you can have a summary of what you are downloading and the details about all the files in one place.

Use filename filtering

Hello

Great job for your work.

For my own needs, i have to accept all pdf files but reject all other like image in signatures...
So i just add a new option in the config rules :
"filenameFromRegexp": ".*\.pdf$",

And then replace in the main code

function Gmail2GDrive() {
  if (!GmailApp) return; // Skip script execution if GMail is currently not available (yes this happens from time to time and triggers spam emails!)
  var config = getGmail2GDriveConfig();
  var label = getOrCreateLabel(config.processedLabel);
  var end, start;
  start = new Date();

  Logger.log("INFO: Starting mail attachment processing.");
  if (config.globalFilter===undefined) {
    config.globalFilter = "has:attachment -in:trash -in:drafts -in:spam";
  }
  for (var ruleIdx=0; ruleIdx<config.rules.length; ruleIdx++) {
    var rule = config.rules[ruleIdx];
    var gSearchExp  = config.globalFilter + " " + rule.filter + " -label:" + config.processedLabel;
    if (config.newerThan != "") {
      gSearchExp += " newer_than:" + config.newerThan;
    }
    var doArchive = rule.archive == true;
    var threads = GmailApp.search(gSearchExp);

    Logger.log("INFO:   Processing rule: "+gSearchExp);
    for (var threadIdx=0; threadIdx<threads.length; threadIdx++) {
      var thread = threads[threadIdx];
      end = new Date();
      var runTime = (end.getTime() - start.getTime())/1000;
      Logger.log("INFO:     Processing thread: "+thread.getFirstMessageSubject() + " (runtime: " + runTime + "s/" + config.maxRuntime + "s)");
      if (runTime >= config.maxRuntime) {
        Logger.log("WARNING: Self terminating script after " + runTime + "s")
        return;
      }
      var messages = thread.getMessages();
      for (var msgIdx=0; msgIdx<messages.length; msgIdx++) {
        var message = messages[msgIdx];
        Logger.log("INFO:       Processing message: "+message.getSubject() + " (" + message.getId() + ")");
        var messageDate = message.getDate();
        var attachments = message.getAttachments();
        for (var attIdx=0; attIdx<attachments.length; attIdx++) {
          var attachment = attachments[attIdx];
          Logger.log("INFO:         Processing attachment: "+attachment.getName());
          
         var match = true;
          if (rule.filenameFromRegexp) {
          var re = new RegExp(rule.filenameFromRegexp);
            match = (attachment.getName()).match(re);
          }
          if (match) {
          try {
            var folder = getOrCreateFolder(rule.folder);
            var file = folder.createFile(attachment);
            if (rule.filenameFrom && rule.filenameTo && rule.filenameFrom == file.getName()) {
              var newFilename = Utilities.formatDate(messageDate, config.timezone, rule.filenameTo.replace('%s',message.getSubject()));
              Logger.log("INFO:           Renaming matched file '" + file.getName() + "' -> '" + newFilename + "'");
              file.setName(newFilename);
            }
            else if (rule.filenameTo) {
              var newFilename = Utilities.formatDate(messageDate, config.timezone, rule.filenameTo.replace('%s',message.getSubject()));
              Logger.log("INFO:           Renaming '" + file.getName() + "' -> '" + newFilename + "'");
              file.setName(newFilename);
            }
            file.setDescription("Mail title: " + message.getSubject() + "\nMail date: " + message.getDate() + "\nMail link: https://mail.google.com/mail/u/0/#inbox/" + message.getId());
            Utilities.sleep(config.sleepTime);
          } catch (e) {
            Logger.log(e);
          }
      }
          else
          {
            Logger.log("INFO:           Rejecting file '" + attachment.getName() + " not matching" + rule.filenameFromRegexp);
          }
        }
      }
      thread.addLabel(label);
      if (doArchive) {
        Logger.log("INFO:     Archiving thread '" + thread.getFirstMessageSubject() + "' ...");
        thread.moveToArchive();
      }
    }
  }
  end = new Date();
  var runTime = (end.getTime() - start.getTime())/1000;
  Logger.log("INFO: Finished mail attachment processing after " + runTime + "s");
}

i hope that could help others users

not an issue more of a request! add a column to csv file with date and or filename.

Hi

I am experimenting with gmail to gdrive to do a bit of automation. very new to scripts so please be nice!!

I have got gmail to drive working for the attachments I have running. thank you very useful!

I would like to add a column(s) of data to particular csv files that the script processes... so for example when the script finds a csv file that meet the criteria it creates a two new column in the csv which contain the file name and the date the script processed the file and moved it to google drive. Is that possible?

many thanks in advance!

G

Existing files are not overwritten on Gdrive

Existing files are not overwritten on Gdrive. This symptom has been reported in issue#19 previously.

  • How to implement the suggested code changes using "file.clear() to remove all the contents of the old file, and then file.append() to insert all of the new contents."?
  • How to implement the suggested code changes using "file.setContent"?

For the time being we are added the following piece in Gmail2Gdrive of code (using the id of the containing folder):
// ====== Remove existing renamed file ======= Added by Soe =======
// --- Delete has to be performed using file id: therefore first convert the actual file name to its file id ---
var file = {title: newFilename, mimeType: 'image/jpeg'};
var myFolder = DriveApp.getFolderById('1F0orpMztVFc3jfCt8HMcT-UuK7tzIvRb'); // myFolder id using key of Graphics subfolder
var allFilesByName = myFolder.getFilesByName(newFilename);
// --- Remove the previous existing renamed file ---
while (allFilesByName.hasNext()) {
var thisFile = allFilesByName.next();
var theFileID = thisFile.getId();
var rtrnFromDLET = Drive.Files.remove(theFileID);
Logger.log('Msg005a Deleted the existing renamed file "' + thisFile + '", ID "' + theFileID + '", rtrnFromDLET: ' + rtrnFromDLET);
};
// ==== Existing renamed file removed ============

    var file = folder.createFile(attachment);  // duplicate previous statement (~ #85) to redefine the 'file' var
    attachment.getName()
    Logger.log("Msg005b:   Renaming '" + file.getName() + "' -> '" + newFilename + "'");
    file.setName(newFilename);

// ========= Remove the stored attachment file ===== Added by Soe =======
var allFilesByName = myFolder.getFilesByName(attachment.getName());
while (allFilesByName.hasNext()) {
var thisFile = allFilesByName.next();
var theFileID = thisFile.getId();
var rtrnFromDLET = Drive.Files.remove(theFileID);
Logger.log('Msg005c Deleted the stored attachment file "' + thisFile + '", ID "' + theFileID + '", rtrnFromDLET: ' + rtrnFromDLET);
};
// =========== Stored attachment file removed =========

Thanks for your help, Regards, Paul,

Creates new parent folder if subfolder doesn't exist

If a parent folder exists โ€“ let's call it 'abc' โ€“ and I write a rule in Config.gs which specifies a subfolder of this parent folder which does not exist โ€“ let's call the non existing subfolder 'xyz' โ€“ the script creates a new parent folder with the same name as the old one, and puts the new subfolder with its files in this new parent folder.

How to recreate:
1: Manually, through the Drive web interface, create a root folder called 'abc'.
2: Create a rule in Config.gs with "folder": "abc/xyz".
3: Execute the script and make sure it hits an item described by the rule.

What I expect:
A newly created folder 'xyz' should be created under the existing folder 'abc'.

What happens:
Another root folder called 'abc' is created with the new subfolder 'xyz' and its file contents.

Conversion from text/html to application/pdf failed

Hi. When attempting to save a thread with no attachments by converting the generated HTML to PDF, the script fails with the following message:

Conversion from text/html to application/pdf failed.

processThreadToPdf @ Code.gs:208
Gmail2Drive @ Code.gs:50

After further dissecting of the code, it seems like the error occurs when calling folder.createFile, but I think the issue originates from the blob.getAs("application/pdf") call.

The issue doesn't seem to be due to quotas exceeding; even though "Files converted" is a qouta'd feature the issue did occur in the first execution, when no quota had been used.

The HTML does not contain any strange or unusual elements, and if I hardcode something simple like the following, the issue still shows up.

<!DOCTYPE html
<html><body><p> hello world </p></body></html>

I'm not sure how reproducible the underlying issue is; the only place I've seen this error message documented is this StackOverflow thread, and none of the answers there seem to work. Unlike in the question, the conversion fail every time for me, and the HTML does not have to be particularly large.

The issue is present regardless of whether the Chrome V8 runtime is enabled or not, though I doubt that matters.

Doesnt process a message/attachment

I sent a test attachment to the mailbox but it is only creating the label it is not however creating/moving the attachment to the specified location in the drive folder.

Please do let me know what further information you would require to assist?

Not working for large attachments (links of GDrive) in email

I tried the script on emails with attachments of size above 25MB (gdrive links). But the script didn't work on the shared links but was able to download the other normal attachments in the same email. I already tried using 'has:drive' in the config file but it didn't work for me, is there any solution to this?

Duplicate files?

How not to save duplicate files? I.e. signature pictures and all that

Add parameter to skip marking a thread as processed

Would be great to have a feature to skip marking a thread as processed if the attachment was not matched to RegExp rule. Such parameter will be very helpful in case if you want to define different folders based on RegExp rule and use only one filter rule.

Potentially, it can increase Quota usage, but if you create rules carefully it will give you more flexibility in saving attachments.

Use subject substring for attachment filename

Usage example (by @CgKortz):

  • Attachment original name is: Image-1.jpg
  • Subject of email is: UDisc iOS Scorecard - McClain Park (Default Layout - 05-28-2016 08:35 AM)

I would like the attachment to be renamed: McClain Park 05-28-2016 08:35 AM
I would think removing the (Default Layout - might be harder but to remove the UDisc iOS Scorecard - should be easy like remove the first 22 characters of the subject before the rename. I googled some and I could not find anything but I also have never scripted so ..... any help would be greatly appreciated.

Publish the project

Hi,
Sorry I'm new to Apps Scripts and I'm not sure how to publish the project to handle it to another user. Also, will this include the time-based trigger that I have created?
Thanks

Add automated tests for GMail2GDrive

The features of GMail2GDrive should be automatically tested to improve code quality and reduce regressions.

Possible unit testing frameworks for Google Apps Script:

The chosen approach is to use clasp for easier overall automation and client-side development as well es QUnit (with gas patch from simula-innovation) for unit tests that can be run from within Google Apps Script.

Since Google clasp enables to use of the existing JavaScript development toolchain with IDE support and many automation possibilities (testing, versioning, deployment, ...).

images missing in the saved PDF file with function "save the thread as a PDF file"

Hi Andreas, thanks for the great work. Not sure if it's only me or an existing issue. The function 'save email thread as PDF file' doesn't seem to include the images in the email body. In my case, all the PDF files saved have empty areas where the images were supposed to fill. Everything works brilliantly except the images were not on the PDF file.

I am not a programmer, so hope anyone can help.

Regards
Alan

Use label as new folder name

Hello, this looks like the perfect tool for what I need to do, I am a complete novice with Google Scripts so apologies if this is a very basic question!
The e-mails I need to filter will have user-defined labels attached, 'Save Attachments', and/or 'Save Mail' and will always have a label 'Job [jobname]'. I need to save the attachments and/or mail to my google drive folder [jobname] - i.e. the label name without the first 4 characters. That folder will already exist on google drive.
What changes do I need to make in the code and config to achieve this?
Many thanks for your help

Groups2TeamDrive?

Hi All
This works great, but I have a new challenge.
I would like to move all attachments to a Google Group address to a team drive.

Basically, I have a virtual fax machine going to a Group. I want those attachments to be automatically inserted into a Team Drive named Faxes.

Any help would be appreciated.

Thanks!

Global filter vs. Processing rules.

Hi, in the Config.gs file:

  1. What is the difference between the "filter" variables in Processing rules and the "globalFilter" variable in Global filter?

  2. On line 8:

"globalFilter": "-in:trash -in:drafts -in:spam",

Are you setting the global filter to NOT include messages in trash, drafts, AND spam? Lastly, do you know if Google Apps Scripts supports the 'and' operator: '&&' and 'AND'?

Thank you!

Error when attempting to save threads and attachments to yyyy/MM folder structures

I'm attempting to have both threads and attachments saved in the same folder, grouped by subject, nested within date-based sub-folders.

I attempted to follow the methodology employed in #36 however I'm getting unexpected results.

I am sure I am getting something wrong with the naming convention for the folder value in config.gs, but I've tried many combinations without success. Sometimes I can get the attachments saving with correctly labelled folders, but the threads get saved in erroneous folder names.


Example:

Payslip.msg (with attachment "PayslipJuly.pdf"),
Sent July 2022
With label 'finance-related-payslips'

Expected outputs (2 files in same path):
Payslips > 2022 > July > Payslip > Payslip.pdf (formerly .msg)
Payslips > 2022 > July > Payslip > PayslipJuly.pdf

Actual output
Payslips > YYYY > MM > Payslip.pdf (formerly .msg)
No attachments.


Artefacts:

Global filter (just to confirm I'm not leaving out anything relevant):

    // Global filter
    "globalFilter": "-in:trash -in:drafts -in:spam",

Offending rule:

// Processing rules:
"rules": [
  {
    // Store threads marked with label "Finance Related/Payslips" in the folder "Payslips" as PDF document.
    "filter": "label:finance-related-payslips",
    "saveThreadPDF": true,
    "folder": "Payslips'/yyyy/MM/%s",
  },

Relevant execution log snippet:

11:16:06 PM
Info
INFO:     Processing thread: FW: Payslip for January 2022 (runtime: 4.757s/280s)
11:16:06 PM
Info
INFO:     Message in trash:false
11:16:06 PM
Info
INFO:       Processing message: FW: Payslip for January 2022 (1820a633ca8c45e0)
11:16:06 PM
Info
INFO:         Processing attachment: PaySlip.pdf
11:16:06 PM
Info
Exception: Invalid argument: Payslips/yyyy/MM/%s
11:16:06 PM
Info
INFO: Saving PDF copy of thread 'FW: Payslip for January 2022'
11:16:07 PM
Info
INFO:   Generating HTML code of thread 'FW: Payslip for January 2022'
11:16:07 PM
Info
INFO:     Message in trash:false
11:16:07 PM
Info
INFO:     Message not in trash: processing.
11:16:09 PM
Info
INFO:     Processing thread: FW: Payslip for December 2021 (runtime: 8.065s/280s)
11:16:09 PM
Info
INFO:     Message in trash:false
11:16:09 PM
Info
INFO:       Processing message: FW: Payslip for December 2021 (1820a6339251c695)
11:16:09 PM
Info
INFO:         Processing attachment: PaySlip.pdf
11:16:09 PM
Info
Exception: Invalid argument: Payslips/yyyy/MM/%s

Appreciate any assistance as I am sure I am getting a lot wrong - I am sure this is a very powerful tool once I get the hang of it!

Add Google Conversion

Would it be possible to add conversion option for attachments? For example, Excel (xls/xlsx) to gSheet and Word (doc/docx) to gDoc.

The simplest code I've found is:
Drive.Files.insert(file, xlsxBlob, {
convert: true
}

Thanks, Andreas

Proposal: A better way to specify storage locations

To get more flexibility for the future it is necessary to redo the filename substitution logic.
Therefore I'd like to get some feedback on the draft below:

Example configuration (DRAFT):

{
    "filter": "has:attachment from:[email protected]",
    "match": {
        "from": "(.+)@example.com",
        "subject": "Prefix - (.*) - Suffix",
        "to": "my\.address\+(.+)@gmail.com" // Support for [email protected] syntax for Gmail addresses
    }
    "attachments": [
        {
            "match": {"name": "Image-([0-9]+)\.jpg"},
            "location": "Folder1/Subfolder1/${match.subject.1}/${email.subject} - ${match.att.1}.jpg",
            // example: subject="Prefix - Test - Suffix", filename="Image-3.jpg" =>
            //   location="Folder1/Subfolder1/Test/Prefix - Test - Suffix - 3.jpg
            "overwrite": true // Overwrite existing files
        },
        {
            "match": {"name": ".+\..+"}, // means *.* or <att.basename>.<att.ext>
            "location": "Folder2/Subfolder2/${att.basename}-${date:yyyy-MM-dd}.${att.ext}",
            // example: subject="Prefix - Test - Suffix", filename="file.txt" =>
            //   location="Folder2/Subfolder2/Test/Prefix - Test - Suffix - 3.jpg
            "overwrite": false // Skip existing files
        }
    ],
},

Substitution parameters (DRAFT):

Let me know, what you think so I can start implementing the feature.

no rule to save in a folder that is the sender's email

not sure that this is an issue so sorry for posting in the wrong place, just wondering if there is a way to save in a folder that is the email address or name of the sender? can only see a few % replacements and sender email address isn't one of them

Archive Message After Processing

I see it's possible to change the label which is applied after an email is processed. Is there a way to specify you would like it archived as well?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.