paulbsd-salt/states/maildb/maildb.py

98 lines
2.3 KiB
Python
Raw 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 MySQLdb
import psycopg2
2020-07-10 00:58:55 +02:00
def DBConfig(configfile):
config = configparser.ConfigParser()
config.read(configfile)
d_dbconfig = {
2020-09-12 17:41:35 +02: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
def ConnectMysqlDB(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)
#conn = MySQLdb.connect(**dbconfig)
2020-07-10 00:58:55 +02:00
return conn, conn.cursor()
def CloseDB(conn):
conn.close()
def CreateDB(conn, cursor):
try:
2020-09-06 16:30:37 +02:00
cursor.execute('''CREATE TABLE IF NOT EXISTS mail (
id serial NOT NULL,
sender text NULL,
recipient text NULL,
"date" timestamp NOT NULL DEFAULT CURRENT_DATE,
"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:
2020-09-06 16:30:37 +02:00
cursor.execute(f"INSERT INTO mail (sender, recipient, content) values ('{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)
2020-09-06 16:30:37 +02: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]
conn, cursor = ConnectMysqlDB(d_dbconfig)
CreateDB(conn, cursor)
InsertMail(conn, cursor, sender, recipient, mailcontent)
CloseDB(conn)
if __name__ == '__main__':
main()