-
Notifications
You must be signed in to change notification settings - Fork 0
/
automail.py
executable file
·350 lines (283 loc) · 9.34 KB
/
automail.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#!/usr/bin/env python3
"""
Simple program to send emails rendered from jinja2templates.
Copyright (C) 2017 tlamer <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
__version__ = '0.4'
import sys
import os
import os.path
import argparse
import logging
import tempfile
import subprocess
import configparser
import smtplib
import email.message
import jinja2
import jinja2.meta
logging.basicConfig(level=logging.WARN)
LOGGER = logging.getLogger(__name__)
# Dictionary with default configuration values.
CONFIG_DEFAULTS = {'starttls': 'yes', 'port': '0'}
def yes_no(question, default="yes"):
"""
Get yes/no input from user.
"""
valid = {
"yes": True,
"y": True,
"no": False,
"n": False,
}
if default is None:
prompt = "[y/n]"
elif default == "yes":
prompt = "[Y/n]"
elif default == "no":
prompt = "[y/N]"
else:
raise ValueError("invalid default answer: {}".format(default))
while True:
sys.stdout.write("{} {} ".format(question, prompt))
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
class StoreDict(argparse.Action):
"""
Custom action to store command line arguments as dictionary.
"""
def __init__(self, option_strings, dest, nargs=None, **kwargs):
super(StoreDict, self).__init__(
option_strings, dest, nargs=nargs, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
my_dict = {}
for item in values:
try:
key, val = item.split('=')
except ValueError:
LOGGER.warning(
"Could not parse '%s'. Parameter in 'key=value' format is expected.",
item)
continue
my_dict[key] = val
setattr(namespace, self.dest, my_dict)
def parse_arguments(cmdline):
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Send emails generated from templates.")
# Arguments with both short and long option strings.
parser.add_argument(
'-c',
'--config',
default='~/.automailrc',
help="Use different configuration file. Default is ~/.automailrc")
parser.add_argument(
'-t', '--template', required=True, help="Template path.")
parser.add_argument(
'-l',
'--list',
action='store_true',
help="List template variables and exit.")
parser.add_argument(
'-n',
'--noninteractive',
action='store_true',
help="Do not edit template manually if possible.")
parser.add_argument(
'-s', '--server', help="Use specific server from the config.")
parser.add_argument(
'-p', '--port', type=int, default=0, help="Use specific port.")
# Arguments with only long option strings.
parser.add_argument('--signature', help="Path to signature text.")
parser.add_argument(
'--dryrun', action='store_true', help="Do not send the message.")
parser.add_argument(
'--starttls',
action='store_true',
default=None,
help=
"Put the SMTP connection in TLS (Transport Layer Security). Default.")
parser.add_argument(
'--nostarttls',
action='store_false',
dest='starttls',
default=None,
help="Do not use STARTTLS.")
parser.add_argument('--host', help="Server address.")
parser.add_argument(
'-d',
'--debug',
action='store_const',
const=logging.DEBUG,
default=logging.WARN,
help="Turn on debug output.")
# Positional arguments are parsed with custom action defined by StoreDict
# class. All positional arguments are used to replate jinja variables used
# in templates.
parser.add_argument(
'jinja_vars',
nargs='*',
action=StoreDict,
metavar='template_variable=variable_value',
help="Template variables like 'name=john'")
return parser.parse_args(cmdline)
def edit_template(template):
"""
Edit template in editor.
"""
out = ""
path = ""
with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as tmpf:
path = tmpf.name
LOGGER.debug("Temporary file: %s", path)
tmpf.write(template)
subprocess.check_call([os.environ["EDITOR"], path])
with open(path, 'rt') as tmpf:
tmpf.seek(0)
out = tmpf.read()
os.remove(path)
return out
def load_config(path):
"""
Load configuration file and add default values.
"""
cfg = configparser.ConfigParser()
cfg['DEFAULT'] = CONFIG_DEFAULTS
with open(os.path.expanduser(path)) as cfgfile:
cfg.read_file(cfgfile)
return cfg
def load_template(path):
"""
Load jinja2 template and return the template object and the set of
variables used in the template.
"""
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(path)))
template = env.get_template(os.path.basename(path))
# Get set of variables used in template.
src = env.loader.get_source(env, os.path.basename(path))[0]
vrs = jinja2.meta.find_undeclared_variables(env.parse(src))
return template, vrs
def parse_message(msg):
"""
Parse headers and message content.
"""
hdrs = {}
body = ""
index = 1
lines = msg.split('\n')
for line in lines:
if line == '':
break
index += 1
LOGGER.debug("Input: %s", line)
key, val = line.split(':', maxsplit=1)
hdrs[key.strip()] = val.strip()
body = '\n'.join(lines[index:])
LOGGER.debug('Message headers: %s', hdrs)
return hdrs, body
def send_message(arg, msg):
"""
Send the message.
"""
LOGGER.debug("Connecting to %s", arg.host)
smtp = smtplib.SMTP(arg.host, port=arg.port)
if arg.starttls:
LOGGER.debug("Use starttls.")
smtp.starttls()
smtp.send_message(msg)
smtp.quit()
def add_signature(sigpath, msg):
"""
Add signature to the message.
"""
with open(os.path.expanduser(sigpath)) as sig:
return msg + '\n' + sig.read()
def apply_cfg(arg):
"""
Apply configuration.
"""
LOGGER.debug("Loading configuration file: %s", arg.config)
cfg = load_config(arg.config)
if not arg.server:
arg.server = cfg['general']['server']
srvcfg = cfg[arg.server]
if arg.starttls is None:
arg.starttls = srvcfg.getboolean('starttls')
if not arg.host:
arg.host = srvcfg['host']
if not arg.port:
arg.port = srvcfg.getint('port')
if not arg.signature:
try:
arg.signature = srvcfg['signature']
except KeyError:
pass
return arg
def main():
"""
Main function.
"""
args = parse_arguments(sys.argv[1:])
LOGGER.setLevel(args.debug)
LOGGER.debug("Command line arguments: %s", args)
apply_cfg(args)
LOGGER.debug("Configuration applied: %s", args)
tmpl, tmpl_vars = load_template(args.template)
# List jinja variables and exit.
if args.list:
print("Undefined template variables: {}".format(tmpl_vars))
return
missing_vars = tmpl_vars - set(args.jinja_vars.keys())
LOGGER.debug("Missing variables: %s", list(missing_vars))
if args.noninteractive:
if missing_vars:
LOGGER.error("Missing jinja variables in noninteractive mode: %s",
missing_vars)
return 1
if args.signature:
message = add_signature(args.signature, tmpl.render(
args.jinja_vars))
else:
message = tmpl.render(args.jinja_vars)
# Print the message in noninteractive mode if dryrun is enabled.
if args.dryrun:
print(message)
else:
for var in missing_vars:
args.jinja_vars[var] = "{{{{ {} }}}}".format(var)
if args.signature:
message = edit_template(
add_signature(args.signature, tmpl.render(args.jinja_vars)))
else:
message = edit_template(tmpl.render(args.jinja_vars))
print(message)
if not args.dryrun:
if not yes_no("\nDo you really want to send the message?", "no"):
return
headers, content = parse_message(message)
mail = email.message.EmailMessage()
mail.set_content(content)
for header in headers:
mail[header] = headers[header]
LOGGER.debug("Adding header: %s: %s", header, headers[header])
mail["User-Agent"] = "Automail/{}".format(__version__)
if not args.dryrun:
send_message(args, mail)
else:
LOGGER.debug("Dry run enabled, message not sent.")
if __name__ == "__main__":
sys.exit(main())