Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import sys
- import smtplib
- from argparse import ArgumentParser
- from configparser import ConfigParser
- from email.message import EmailMessage
- from pathlib import Path
- def make_mail(body, subject, to_, creds):
- msg = EmailMessage()
- msg.set_content(body)
- msg['Subject'] = subject
- msg['From'] = creds['email']
- msg['To'] = to_
- return msg
- def send(message, creds, debug=False, verbose=False):
- with smtplib.SMTP(creds['host'], creds['port']) as smtp:
- if verbose:
- smtp.set_debuglevel(1)
- code, reply = smtp.starttls()
- if debug:
- print(reply.decode(), file=sys.stderr)
- code, reply = smtp.login(creds['user'], creds['password'])
- if debug:
- print(reply.decode(), file=sys.stderr)
- smtp.send_message(message)
- def load_config():
- script_path = Path(sys.argv[0]).absolute().parent
- config_name = '.email-creds'
- config = script_path / config_name
- cfg = ConfigParser()
- if config.exists():
- cfg.read([config])
- return cfg
- else:
- cfg['email'] = {
- 'host': 'securesmtp.t-online.de',
- 'port': 587,
- 'timeout': 5,
- 'email': 'email@domain.tld',
- 'user': 'email@domain.tld',
- 'password': 'not set',
- }
- with config.open('w') as fd:
- cfg.write(fd)
- print('Written config to', config, file=sys.stderr)
- print('Change the settings inside this config and execute the program again', file=sys.stderr)
- return None
- def main(message, subject, to, debug=False, verbose=False):
- cfg = load_config()
- if cfg is None:
- sys.exit(1)
- msg = make_mail(message, subject, to, cfg['email'])
- send(msg, cfg['email'], debug, verbose)
- if __name__ == '__main__':
- parser = ArgumentParser()
- parser.add_argument('message', help="Message you want to send")
- parser.add_argument('subject', help="The subject of the message")
- parser.add_argument('to', help="Receiver of the e-mail")
- parser.add_argument('-d', '--debug', action='store_true', help='Show debug info about login and starttls.')
- parser.add_argument('-v', '--verbose', action='store_true', help='Show messages form smtp server')
- args = parser.parse_args()
- main(**vars(args))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement