diff --git a/.gitignore b/.gitignore index b5a43d3..6932f68 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +config.py # ---> Linux *~ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..08e8ddd --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "fstools"] + path = fstools + url = https://git.mount-mockery.de/pylib/fstools.git +[submodule "report"] + path = report + url = https://git.mount-mockery.de/pylib/report.git diff --git a/__install__.py b/__install__.py new file mode 100644 index 0000000..9ff7925 --- /dev/null +++ b/__install__.py @@ -0,0 +1,41 @@ +#!/bin/python +# +import os +import sys + +SERVICE_FILE = """ +[Unit] +Description=File2Mail Service +After=network-online.target +Wants=network-online.target +[Service] +User=%(UID)d +Group=%(GID)d +ExecStart=%(MY_PATH)s/file2mail.sh +Type=simple +[Install] +WantedBy=default.target +""" + + +def help(): + print("Usage: prog ") + +if __name__ == "__main__": + if len(sys.argv) == 4: + try: + uid = int(sys.argv[1]) + gid = int(sys.argv[2]) + except ValueError: + help() + else: + if os.path.isdir(sys.argv[3]): + with open(os.path.join(sys.argv[3], 'file2mail.service'), "w") as fh: + fh.write(SERVICE_FILE % { + "MY_PATH": os.path.dirname(os.path.abspath(__file__)), + "UID": uid, + "GID": gid}) + else: + help() + else: + help() diff --git a/config_example/config.py b/config_example/config.py new file mode 100644 index 0000000..28d93a2 --- /dev/null +++ b/config_example/config.py @@ -0,0 +1,14 @@ +# Folder to be monitored for new files +TARGET_FOLDER = "/home/scan" + +# Recipiant for the files found in TARGET_PATH +SEND_TO = "scan@mount-mockery.de" + +# Sender +SEND_FROM = "Scanner-Buchen " +SMTP_SERVER = "mount-mockery.de" +SMTP_USER = "smtp-sendmail" +SMTP_PASSWORD = "----XXX----" + +# Possible log-levels: DEBUG, INFO, WARNING, ERROR +LOG_LEVEL = "INFO" diff --git a/file2mail.py b/file2mail.py new file mode 100644 index 0000000..f6f7a59 --- /dev/null +++ b/file2mail.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- +import config +import fstools +import json +import logging +import mail +import os +import report +import time + +LOCK_FILE = os.path.join(config.TARGET_FOLDER, "lock") +PID = os.getpid() + +logger = logging.getLogger('root') +report.stdoutLoggingConfigure(log_name_lvl=[('root', config.LOG_LEVEL), ]) + + +if __name__ == "__main__": + while True: + # Check if LOCK_FILE EXISTS + if not os.path.exists(LOCK_FILE): + # Create LOCK_FILE + with open(LOCK_FILE, 'w') as fh: + fh.write(str(PID)) + logger.debug("Creating lock-file %s with PID %d", LOCK_FILE, PID) + # Read LOCK_FILE content + with open(LOCK_FILE, 'r') as fh: + lf_pid = json.loads(fh.read()) + # Check if LOCK_FILE has my PID + if lf_pid == PID: + # Scan for files to send + for filename in fstools.filelist(config.TARGET_FOLDER): + # Exclude LOCK_FILE + if filename != LOCK_FILE: + logger.info("Found %s to send via E-Mail to %s.", filename, config.SEND_TO) + # Send File as E-Mail + try: + mail.send_mail( + config.SEND_FROM, + config.SEND_TO, + "Gesanntes Dokument - %s" % os.path.basename(filename), + "Hier ist das gescannte Dokument vom Scanner in Buchen:", + files=[filename], + server=config.SMTP_SERVER, + username=config.SMTP_USER, + password=config.SMTP_PASSWORD + ) + except Exception: + logger.exception("Exception while sending an E-Mail") + else: + # Remove file + logger.debug("Removing file %s", filename) + os.remove(filename ) + # Remove LOCK_FILE + logger.debug("Removing lock-file %s", LOCK_FILE) + os.remove(LOCK_FILE) + else: + logger.warning("LOCK_FILE has PID %d and this proces %d. No action!", lf_pid, PID) + else: + logger.warning("LOCK_FILE %s already exists. No action!", LOCK_FILE) + time.sleep(60) diff --git a/file2mail.sh b/file2mail.sh new file mode 100755 index 0000000..6ff6dce --- /dev/null +++ b/file2mail.sh @@ -0,0 +1,4 @@ +#!/bin/sh +# +BASEPATH=`dirname $0` +python $BASEPATH/file2mail.py diff --git a/fstools b/fstools new file mode 160000 index 0000000..c10e879 --- /dev/null +++ b/fstools @@ -0,0 +1 @@ +Subproject commit c10e8792abb05671dab6de51cdadda3bf8ead50f diff --git a/mail.py b/mail.py new file mode 100644 index 0000000..657ad8b --- /dev/null +++ b/mail.py @@ -0,0 +1,48 @@ +import smtplib +from pathlib import Path +from email.mime.multipart import MIMEMultipart +from email.mime.base import MIMEBase +from email.mime.text import MIMEText +from email.utils import COMMASPACE, formatdate +from email import encoders + + +def send_mail(send_from, send_to, subject, message, files=[], + server="localhost", username='', password='', + use_tls=True): + """Compose and send email with provided info and attachments. + + Args: + send_from (str): from name + send_to (list[str]): to name(s) + subject (str): message title + message (str): message body + files (list[str]): list of file paths to be attached to email + server (str): mail server host name + username (str): server auth username + password (str): server auth password + use_tls (bool): use TLS mode + """ + msg = MIMEMultipart() + msg['From'] = send_from + msg['To'] = send_to + msg['Date'] = formatdate(localtime=True) + msg['Subject'] = subject + + msg.attach(MIMEText(message)) + + for path in files: + part = MIMEBase('application', "octet-stream") + with open(path, 'rb') as file: + part.set_payload(file.read()) + encoders.encode_base64(part) + part.add_header('Content-Disposition', + 'attachment; filename={}'.format(Path(path).name)) + msg.attach(part) + + smtp = smtplib.SMTP(server) + if use_tls: + smtp.starttls() + smtp.login(username, password) + smtp.sendmail(send_from, send_to.split(', '), msg.as_string()) + smtp.quit() diff --git a/report b/report new file mode 160000 index 0000000..b53dd30 --- /dev/null +++ b/report @@ -0,0 +1 @@ +Subproject commit b53dd30eae1d679b7eec4999bec50aed55bc105b