-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinymta
executable file
·217 lines (177 loc) · 6.29 KB
/
tinymta
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
#!/usr/bin/env python3
# Author: Jan Larres <jan@majutsushi.net>
# License: MIT/X11
#
# Extremely simple MTA that accepts local mail by simulating a sendmail binary
# and forwards it to a real mail server. Heavily inspired by ssmtp.
#
# Copy/symlink it to:
# - /usr/sbin/sendmail
# - /usr/lib/sendmail
# - /usr/sbin/mailq
# - /usr/sbin/newaliases
#
# Example config file (/etc/tinymta.conf or ~/.config/tinymta.conf):
#
# [DEFAULT]
# recipient = foo@example.com
# smarthost = mail.example.com
# username = foo
# password = password
import argparse
import configparser
import email
from email.utils import getaddresses
import os
import pwd
from smtplib import SMTP_SSL
import socket
import sys
import syslog
from typing import Any, List, Optional, Sequence, Union
unsupported_args = ["ba", "bd", "bs", "bt", "bv", "bz"]
ignored_args = [
("B", 1),
("bi", 0),
("bm", 0),
("E", 0),
("h", 1),
("i", 0),
("m", 0),
("M", 1),
("n", 0),
("N", 1),
("o", 1),
("R", 1),
]
# Unsupported arguments raise an error
class UnsupportedAction(argparse.Action):
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: Union[str, Sequence[Any], None],
option_string: Optional[str] = None,
) -> None:
print("%r option not supported" % option_string)
sys.exit(1)
class IgnoredAction(argparse.Action):
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: Union[str, Sequence[Any], None],
option_string: Optional[str] = None,
) -> None:
pass
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="tinymta", add_help=False)
parser.add_argument("rcpts", nargs="*")
parser.add_argument("-F", dest="fullname")
parser.add_argument("-f", "-r", dest="fromaddr")
parser.add_argument("-t", action="store_true", dest="extract_rcpts", default=False)
parser.add_argument("-d", "--debug", action="store_true", default=False)
for arg in unsupported_args:
parser.add_argument("-" + arg, action=UnsupportedAction, nargs=0)
for [arg, nargs] in ignored_args:
parser.add_argument("-" + arg, action=IgnoredAction, nargs=nargs)
# simulated args
parser.add_argument("-bp", action="store_true", default=False)
parser.add_argument("-q", nargs="?", default=argparse.SUPPRESS)
return parser.parse_args()
# Print message and exit successfully
def exit_success(s: str) -> None:
print(s)
sys.exit(0)
# Log error message to syslog and exit with an error code
def die(s: Union[str, Exception], msg: Optional[email.message.Message] = None) -> None:
syslog.syslog(syslog.LOG_WARNING, repr(s))
if msg is not None:
home = pwd.getpwuid(os.getuid()).pw_dir
path = os.path.join(home, "dead.letter")
syslog.syslog(syslog.LOG_WARNING, "Writing mail to " + path)
nl = "\n" if os.path.exists(path) else ""
with open(path, "a") as f:
f.write(nl)
f.write(msg.as_string())
if isinstance(s, Exception) and sys.stdout.isatty():
raise s
print(str(s))
sys.exit(1)
# Get recipients from the message and command line arguments, then map them to
# remote recipients according to the config file(s)
def get_recipients(
args: argparse.Namespace,
msg: email.message.Message,
config: configparser.ConfigParser,
) -> List[str]:
rcpts = [a[1] for a in getaddresses(args.rcpts)]
if args.extract_rcpts:
for header in ["To", "Cc", "Bcc"]:
addresses = msg.get_all(header)
if addresses is None:
continue
rcpts += [a[1] for a in getaddresses(addresses)]
result = []
for rcpt in rcpts:
user = rcpt.split("@")[0]
conf = config[user] if user in config else config["DEFAULT"]
result.append(conf["recipient"])
return result
# Main function
def main(args: argparse.Namespace) -> None:
name = os.path.basename(sys.argv[0])
# Simulate the "mailq" and "newaliases" commands
if name == "mailq" or args.bp or "q" in args:
exit_success("%s: Mail queue is empty" % name)
if name == "newaliases":
exit_success("%s: Aliases are not used in tinymta" % name)
if len(args.rcpts) == 0 and not args.extract_rcpts:
exit_success("%s: No recipients supplied - mail will not be sent" % name)
# Parse mail passed in through stdin
msg = email.message_from_bytes(sys.stdin.buffer.read())
try:
syslog.openlog(ident="tinymta", facility=syslog.LOG_MAIL)
# Get user info from passwd file
pw = pwd.getpwuid(os.getuid())
# Read configuration, with user config overriding system-wide one
# TODO: Proper per-user/recipient configuration
config = configparser.ConfigParser()
config.read(
["/etc/tinymta.conf", os.path.join(pw.pw_dir, ".config/tinymta.conf")]
)
defaultconf = config["DEFAULT"]
rcpts = get_recipients(args, msg, config)
if len(rcpts) == 0:
die("No recipients specified", msg)
# Construct a "From" header from explicit argument, existing header,
# or username
fromaddr = msg.get("From")
if args.fromaddr is not None:
fromaddr = args.fromaddr
if fromaddr is None:
fromaddr = pw.pw_name
if "@" not in fromaddr:
fromaddr += "@" + socket.getfqdn()
if "From" in msg:
msg.replace_header("From", fromaddr)
else:
msg.add_header("From", fromaddr)
if msg.get("Date") is None:
msg.add_header("Date", email.utils.formatdate(localtime=True))
# Send the mail
with SMTP_SSL(defaultconf["smarthost"]) as smtp:
if args.debug:
smtp.set_debuglevel(1)
smtp.login(defaultconf["username"], defaultconf["password"])
smtp.send_message(msg, from_addr=fromaddr, to_addrs=rcpts)
syslog.syslog(
syslog.LOG_INFO,
"Sent mail with subject %r to %s" % (msg.get("Subject"), str(rcpts)),
)
except Exception as e: # pylint: disable=broad-except
if sys.stdin.isatty():
raise e
die(e, msg)
if __name__ == "__main__":
main(parse_args())