Skip to content

Commit

Permalink
eml_unpack_attachments: add sanity checks for file extension and type
Browse files Browse the repository at this point in the history
  • Loading branch information
dezeroku committed Oct 1, 2024
1 parent dc729e3 commit 1d140e6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ On top of that, there are golang utilities:

- `s3_monitor`, monitors remote bucket for changes and downloads files if new ones were added (also removing them from the bucket).
Adds `.eml` suffix to the files
- `eml_unpack_attachments`, monitors local directory for new files and unpacks attachments from them (assumes that new files are .eml)
- `eml_unpack_attachments`, monitors local directory for new `.eml` files and unpacks attachments from them

## How does it work?

Expand Down Expand Up @@ -118,6 +118,8 @@ In both cases you'll have to set few environment variables for the program to wo
- INPUT_DIRECTORY (local directory to monitor for `.eml` files)
- OUTPUT_DIRECTORY (where to put the unpacked attachments)

After the `.eml` file is unpacked, it is removed as it's not needed anymore.

## But why?

I have recently started using [Paperless-ngx](https://docs.paperless-ngx.com/) that supports documents consumption via e-mail.
Expand Down
22 changes: 19 additions & 3 deletions eml_unpack_attachments/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"log"
"os"
"path"
"strings"

"github.com/DusanKasan/parsemail"
"github.com/fsnotify/fsnotify"
Expand All @@ -24,9 +25,24 @@ func requireEnvVariable(name string) string {
return value
}

func processEmail(filename string, outputDirectory string) error {
func processNewFile(filename string, outputDirectory string) error {
log.Print("Processing file: ", filename)

if !strings.HasSuffix(filename, ".eml") {
log.Print("File doesn't have .eml extension, skipping: ", filename)
return nil
}

fileInfo, err := os.Stat(filename)
if err != nil {
return err
}

if fileInfo.IsDir() {
log.Print("File is a directory, skipping: ", filename)
return nil
}

reader, err := os.Open(filename)
if err != nil {
return err
Expand Down Expand Up @@ -85,7 +101,7 @@ func main() {
if event.Has(fsnotify.Create) {
log.Print("New file: ", event.Name)

err := processEmail(event.Name, outputDirectory)
err := processNewFile(event.Name, outputDirectory)
if err != nil {
log.Print(err)
}
Expand Down Expand Up @@ -114,7 +130,7 @@ func main() {
}

for _, file := range files {
err := processEmail(path.Join(inputDirectory, file.Name()), outputDirectory)
err := processNewFile(path.Join(inputDirectory, file.Name()), outputDirectory)
if err != nil {
log.Fatal(err)
}
Expand Down

0 comments on commit 1d140e6

Please sign in to comment.