testmail ¶
Save into '/usr/local/bin/testmail', then:
chmod +x /usr/local/bin/testmail
#!/usr/bin/env python3 import os import configparser from pathlib import Path import argparse def run_command(command, dry_run): print("\x1b[1;37;40m" + command + "\x1b[0m") if not dry_run: os.system(command) class Config(): def __init__(self): self._config = configparser.ConfigParser() if not self.get_config_filename().exists(): self._config['general'] = { 'counter': 1, } self.save_config() print(f"Default config written to {self.get_config_filename()}") self.read_config() def get_config_filename(self): return Path(__file__).parent / "testmail.ini" def read_config(self): self._config.read(self.get_config_filename()) def save_config(self): with open(self.get_config_filename(), 'w') as f: self._config.write(f) def get_counter(self, increment=True): value = self._config.getint('general', 'counter') if increment: self.increment_counter() return value def increment_counter(self): self._config['general']['counter'] = str(self.get_counter(increment=False) + 1) self.save_config() def reset_counter(self): self._config['general']['counter'] = '1' self.save_config() def get_section(self, section): section = self._config[section] return dict(section.items()) def build_swaks_command(counter, config, recipient): """ swaks --to you@yourdomain.com \ --from smtp@helpdesk.brainstorm.it \ --server 127.0.0.1 \ --auth LOGIN \ --auth-user smtp@helpdesk.brainstorm.it \ --auth-password e67ca7ef5c85e56a35e7a22b6be4b2d5 \ --port 587 Sample section in config file: [swaks] from = "Brainstorm helpdesk <smtp@helpdesk.brainstorm.it>" server = 127.0.0.1 auth = LOGIN auth-user = smtp@helpdesk.brainstorm.it auth-password = ********************** port = 587 """ section = config.get_section('swaks') command = f"swaks --to {recipient}" command += f' --header "Subject: Test mail {counter}"' for key, value in section.items(): command += f" --{key} {value}" return command def build_mail_command(counter, recipient): command = 'echo "Test mail %d; created on: `date`" | mail -s "Test mail %d" %s' % ( counter, counter, recipient, ) return command if __name__ == '__main__': parser = argparse.ArgumentParser(description="Sends a test email to the specified recipient") parser.add_argument('recipient') parser.add_argument('--use-swaks', '-s', action='store_true') parser.add_argument('--dry-run', '-d', action='store_true') args = parser.parse_args() config = Config() counter = config.get_counter(increment=not args.dry_run) if args.use_swaks: command = build_swaks_command(counter, config, args.recipient) else: command = build_mail_command(counter, args.recipient) run_command(command, args.dry_run)