|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import psycopg2 |
| 5 | +import smtplib |
| 6 | +import sys |
| 7 | +import yaml |
| 8 | + |
| 9 | + |
| 10 | +if __name__ == "__main__": |
| 11 | + parser = argparse.ArgumentParser("Email tester") |
| 12 | + parser.add_argument('db', help='Name of database (looked up in config.yaml) t connect to') |
| 13 | + parser.add_argument('id', type=int, help='ID of email entry to send') |
| 14 | + parser.add_argument('recipient', help='Email address of recipient to send to') |
| 15 | + |
| 16 | + args = parser.parse_args() |
| 17 | + |
| 18 | + with open('config.yaml') as f: |
| 19 | + config = yaml.load(f, Loader=yaml.SafeLoader) |
| 20 | + |
| 21 | + if args.db not in config['db']: |
| 22 | + print("Non-existing db specified") |
| 23 | + sys.exit(1) |
| 24 | + |
| 25 | + if isinstance(config['mail']['password'], str): |
| 26 | + password = config['mail']['password'] |
| 27 | + elif isinstance(config['mail']['password'], dict): |
| 28 | + import secretstorage |
| 29 | + coll = secretstorage.get_default_collection(secretstorage.dbus_init()) |
| 30 | + if coll.is_locked(): |
| 31 | + coll.unlock() |
| 32 | + r = list(coll.search_items(config['mail']['password'])) |
| 33 | + if len(r) == 0: |
| 34 | + print("Could not find password in secret storage.") |
| 35 | + sys.exit(1) |
| 36 | + elif len(r) > 1: |
| 37 | + print("Found more than one password, try again.") |
| 38 | + sys.exit(1) |
| 39 | + password = r[0].get_secret().decode() |
| 40 | + else: |
| 41 | + print("Invalid type for password in configuration") |
| 42 | + sys.exit(1) |
| 43 | + |
| 44 | + # Connect to db and get message |
| 45 | + dbconn = psycopg2.connect(config['db'][args.db]) |
| 46 | + curs = dbconn.cursor() |
| 47 | + curs.execute("SELECT fullmsg FROM mailqueue_queuedmail WHERE id=%(id)s", { |
| 48 | + 'id': args.id, |
| 49 | + }) |
| 50 | + r = curs.fetchall() |
| 51 | + dbconn.close() |
| 52 | + |
| 53 | + if len(r) == 0: |
| 54 | + print("Email not found") |
| 55 | + sys.exit(1) |
| 56 | + |
| 57 | + msg = r[0][0] |
| 58 | + |
| 59 | + # Now do it! |
| 60 | + smtp = smtplib.SMTP(host=config['mail']['server'], port=config['mail']['port']) |
| 61 | + smtp.starttls() |
| 62 | + smtp.login(user=config['mail']['user'], password=password) |
| 63 | + |
| 64 | + smtp.sendmail(config['mail']['sender'], args.recipient, msg) |
| 65 | + |
| 66 | + smtp.quit() |
| 67 | + |
| 68 | + print("Sent.") |
0 commit comments