paulbsd-salt/states/maildb/templates/maildb.py

99 lines
2.4 KiB
Python
Raw Permalink Normal View History

2020-07-10 00:58:55 +02:00
#!/usr/bin/env python3
import argparse
import sys
import configparser
from email.utils import parseaddr
2020-09-06 16:30:37 +02:00
import email
import psycopg2
2020-07-10 00:58:55 +02:00
def DBConfig(configfile):
config = configparser.ConfigParser()
config.read(configfile)
d_dbconfig = {
2024-01-27 10:42:03 +01:00
"host" : config.get("maildb", "hostname"),
"user" : config.get("maildb", "username"),
"passwd" : config.get("maildb", "password"),
"db" : config.get("maildb", "database")
2020-07-10 00:58:55 +02:00
}
return d_dbconfig
2021-11-27 13:25:29 +01:00
def ConnectDB(dbconfig):
2020-09-06 16:30:37 +02:00
connstr = f"host={dbconfig['host']} dbname={dbconfig['db']} user={dbconfig['user']} password={dbconfig['passwd']}"
conn = psycopg2.connect(connstr)
2020-07-10 00:58:55 +02:00
return conn, conn.cursor()
def CloseDB(conn):
conn.close()
def CreateDB(conn, cursor):
try:
2024-01-27 10:42:03 +01:00
cursor.execute('''
CREATE TABLE IF NOT EXISTS mail (
id serial NOT NULL,
sender text NULL,
recipient text NULL,
"date" timestamp NOT NULL DEFAULT NOW(),
"content" text NULL,
CONSTRAINT mail_pkey PRIMARY KEY (id)
)
''')
2020-07-10 00:58:55 +02:00
conn.commit()
except Exception as e:
print(e)
def InsertMail(conn, cursor, sender, recipient, content):
try:
2024-01-13 13:26:48 +01:00
cursor.execute("PREPARE InsertMail as INSERT INTO mail (sender, recipient, content) values ($1, $2, $3);")
cursor.execute("EXECUTE InsertMail (%s, %s, %s);", (sender, recipient, content))
2020-07-10 00:58:55 +02:00
conn.commit()
except Exception as e:
print(e)
def ParseMail(input_data):
content = ""
for line in input_data:
if line != "":
content += line
2020-09-06 16:30:37 +02:00
2020-07-10 00:58:55 +02:00
msgobj = email.message_from_string(content)
2024-01-27 10:42:03 +01:00
sender = parseaddr(msgobj["From"])[1]
recipient = parseaddr(msgobj["To"])[1]
2020-07-10 00:58:55 +02:00
return sender, recipient, content
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", help="config file path", default="maildb.cfg")
parser.add_argument("sender", help="sender")
parser.add_argument("recipient", help="recipient")
args = parser.parse_args()
d_dbconfig = DBConfig(args.config)
maildata = ParseMail(sys.stdin)
sender = maildata[0]
recipient = maildata[1]
mailcontent = maildata[2]
2021-11-27 13:25:29 +01:00
conn, cursor = ConnectDB(d_dbconfig)
2020-07-10 00:58:55 +02:00
CreateDB(conn, cursor)
InsertMail(conn, cursor, sender, recipient, mailcontent)
CloseDB(conn)
2024-01-27 10:42:03 +01:00
if __name__ == "__main__":
2020-07-10 00:58:55 +02:00
main()