| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
"""Mock the mailx / mailutils `mail` command""" |
| 4 |
|
| 5 |
import argparse |
| 6 |
import smtplib |
| 7 |
import sys |
| 8 |
import os |
| 9 |
|
| 10 |
parser = argparse.ArgumentParser( |
| 11 |
description='Cylc functional tests mail command.') |
| 12 |
parser.add_argument( |
| 13 |
'-s', metavar='subject', dest='subject', type=str, help='e-mail subject') |
| 14 |
parser.add_argument( |
| 15 |
'-r', metavar='reply_to', dest='sender', type=str, |
| 16 |
help='e-mail reply-to address') |
| 17 |
parser.add_argument( |
| 18 |
'to', metavar='to', type=str, help='e-mail destination address') |
| 19 |
parser.add_argument( |
| 20 |
'body', metavar='body', nargs='?', type=argparse.FileType('r'), |
| 21 |
default=sys.stdin, help='e-mail body') |
| 22 |
|
| 23 |
smtp_server = os.getenv('smtp') |
| 24 |
try: |
| 25 |
host, port = smtp_server.split(':') |
| 26 |
port = int(port) |
| 27 |
except (AttributeError, ValueError): |
| 28 |
raise OSError( |
| 29 |
'The environment variable "smtp" must be set to a string of the form ' |
| 30 |
'"host:port" (e.g. "localhost:8025") for the mocked mail command ' |
| 31 |
'to work.') |
| 32 |
|
| 33 |
args = parser.parse_args() |
| 34 |
|
| 35 |
sender_email = args.sender |
| 36 |
receiver_email = args.to |
| 37 |
message = f"""\ |
| 38 |
Subject: {args.subject} |
| 39 |
|
| 40 |
{args.body.read()}""" |
| 41 |
|
| 42 |
# https://realpython.com/python-send-email/ |
| 43 |
with smtplib.SMTP(host, port) as server: |
| 44 |
server.sendmail(sender_email, receiver_email, message) |