2021-05-19 18:07:42 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
""" Test Email client """
|
|
|
|
import datetime
|
|
|
|
import logging
|
|
|
|
import sys
|
|
|
|
|
|
|
|
import getpass
|
2021-05-19 19:19:57 +02:00
|
|
|
from mako.template import Template as MakoTemplate
|
2021-05-19 18:07:42 +02:00
|
|
|
|
|
|
|
from mylib.scripts.helpers import get_opts_parser, add_email_opts
|
|
|
|
from mylib.scripts.helpers import init_logging, init_email_client
|
|
|
|
|
|
|
|
|
|
|
|
log = logging.getLogger('mylib.scripts.email_test')
|
|
|
|
|
2021-05-19 19:19:57 +02:00
|
|
|
|
|
|
|
def main(argv=None): # pylint: disable=too-many-locals,too-many-statements
|
2021-05-19 18:07:42 +02:00
|
|
|
""" Script main """
|
|
|
|
if argv is None:
|
|
|
|
argv = sys.argv[1:]
|
|
|
|
|
|
|
|
# Options parser
|
|
|
|
parser = get_opts_parser(just_try=True)
|
|
|
|
add_email_opts(parser)
|
|
|
|
|
|
|
|
test_opts = parser.add_argument_group('Test email options')
|
|
|
|
|
|
|
|
test_opts.add_argument(
|
|
|
|
'-t', '--to',
|
|
|
|
action="store",
|
|
|
|
type=str,
|
|
|
|
dest="test_to",
|
|
|
|
help="Test email recipient",
|
|
|
|
)
|
|
|
|
|
|
|
|
test_opts.add_argument(
|
|
|
|
'-m', '--mako',
|
|
|
|
action="store_true",
|
|
|
|
dest="test_mako",
|
|
|
|
help="Test mako templating",
|
|
|
|
)
|
|
|
|
|
|
|
|
options = parser.parse_args()
|
|
|
|
|
|
|
|
if not options.test_to:
|
|
|
|
parser.error('You must specify test email recipient using -t/--to parameter')
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
# Initialize logs
|
|
|
|
init_logging(options, 'Test EmailClient')
|
|
|
|
|
|
|
|
if options.email_smtp_user and not options.email_smtp_password:
|
|
|
|
options.email_smtp_password = getpass.getpass('Please enter SMTP password: ')
|
|
|
|
|
|
|
|
log.info('Initialize Email client')
|
|
|
|
email_client = init_email_client(
|
|
|
|
options,
|
|
|
|
templates=dict(
|
|
|
|
test=dict(
|
|
|
|
subject="Test email",
|
|
|
|
text=(
|
|
|
|
"Just a test email sent at {sent_date}." if not options.test_mako else
|
|
|
|
MakoTemplate("Just a test email sent at ${sent_date}.")
|
|
|
|
),
|
|
|
|
html=(
|
|
|
|
"<strong>Just a test email.</strong> <small>(sent at {sent_date})</small>" if not options.test_mako else
|
|
|
|
MakoTemplate("<strong>Just a test email.</strong> <small>(sent at ${sent_date})</small>")
|
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
log.info('Send a test email to %s', options.test_to)
|
|
|
|
if email_client.send(options.test_to, template='test', sent_date=datetime.datetime.now()):
|
|
|
|
log.info('Test email sent')
|
|
|
|
sys.exit(0)
|
|
|
|
log.error('Fail to send test email')
|
|
|
|
sys.exit(1)
|