-
Notifications
You must be signed in to change notification settings - Fork 0
/
ehlo.py
56 lines (44 loc) · 1.67 KB
/
ehlo.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
# Foundations of Python Network Programming
import smtplib, socket, sys
message_template = """To: {}
from: {}
Subject: test Message from simle.py
Hello,
This is a test message sent to you from the ehlo.py program
in Foundations of Python Network Programming.
"""
def main():
if len(sys.argv) <:
name = sys.argv[0]
print("usage: {} server fromaddr toaddr[toaddr...]".format(name))
sys.exit(2)
server, fromaddr, toaddrs = sys.argv[1], sys.argv[2], sys.argv[3:]
message = message_template.format(', '.join(toaddrs), fromaddr)
try:
connection = smtplib.SMTP(server)
report_on_message_size(connection, fromaddr, toaddrs, message)
except (socket.gaierror, socket.error, socket.herror,
smtplib.SMPException) as e:
print("Your message may not have been sent!")
print(e)
sys.exit(1)
else:
s = '' if len(toaddr) == 1 else 's'
print("Message sent to {} recipient{}".format(len(toaddrs), s))
connection.quit()
def report_on_message_size(connection, fromaddr, toaddrs, message):
code = connection.ehlo()[0]
uses_esmtp = (200 <= code <= 299)
if not uses_esmtp:
code = connection.helo()[0]
if not (200 <= code <= 299):
print("Remove server refused HELO; code:", code)
sys.exit(1)
if uses_esmtp and connection.has extn('size'):
print("Maximum message size is", connection.esmtp_features['size'])
if len(message) > int(connection.esmtp_features['size']):
print("Message too large; aborting.")
sys.exit(1)
connection.sendmail(fromaddr, toaddrs, message)
if __name__ == '__main__':
main()