paulbsd-salt/states/maildb/maildb.py

89 lines
2.1 KiB
Python
Raw Normal View History

2020-07-10 00:58:55 +02:00
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import argparse
import sys
import MySQLdb
import configparser
import email
from email.utils import parseaddr
def DBConfig(configfile):
config = configparser.ConfigParser()
config.read(configfile)
d_dbconfig = {
'host' : config.get("maildb", "hostname"),
'user' : config.get("maildb", "username"),
'passwd' : config.get("maildb", "password"),
'db' : config.get("maildb", "database")
}
return d_dbconfig
def ConnectMysqlDB(dbconfig):
conn = MySQLdb.connect(**dbconfig)
return conn, conn.cursor()
def CloseDB(conn):
conn.close()
def CreateDB(conn, cursor):
try:
cursor.execute('''CREATE TABLE IF NOT EXISTS mail (id int(10) PRIMARY KEY AUTO_INCREMENT, sender varchar(50), recipient varchar(50), date datetime NOT NULL DEFAULT current_timestamp(), content mediumtext);''')
conn.commit()
except Exception as e:
print(e)
def InsertMail(conn, cursor, sender, recipient, content):
try:
cursor.execute("INSERT INTO mail (sender, recipient, content) values ('%s','%s','%s')" % (sender, recipient, content))
conn.commit()
except Exception as e:
print(e)
def ParseMail(input_data):
content = ""
for line in input_data:
if line != "":
content += line
msgobj = email.message_from_string(content)
sender = email.utils.parseaddr(msgobj['From'])[1]
recipient = email.utils.parseaddr(msgobj['To'])[1]
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()