Skip to content

Commit 1980fa3

Browse files
committed
Uplift script to be compatible with python3
This script now uses python3.9+ compatible idioms to function.
1 parent 04ae9ab commit 1980fa3

File tree

1 file changed

+94
-63
lines changed
  • profiles/base/freebsd/scratch/scripts/python

1 file changed

+94
-63
lines changed

profiles/base/freebsd/scratch/scripts/python/sendmail.py

Lines changed: 94 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -14,31 +14,49 @@
1414
Enji Cooper, October 2013
1515
"""
1616

17-
from email.mime.multipart import MIMEMultipart
18-
from email.mime.text import MIMEText
19-
from email.Utils import formatdate
17+
import argparse
2018
import getpass
19+
import logging
2120
import os
2221
import select
2322
import smtplib
2423
import socket
2524
import sys
2625
import time
26+
from email.mime.multipart import MIMEMultipart
27+
from email.mime.text import MIMEText
28+
from email.utils import formatdate
29+
from typing import Optional
2730

2831

29-
def add_attachments(attachment_files):
32+
DEBUG = False
33+
34+
35+
def add_attachments(attachment_files: list[os.PathLike]) -> list[MIMEText]:
3036
attachments = []
3137
for attachment_file in attachment_files:
32-
attachment = MIMEText(open(attachment_file, 'rb').read(),
33-
_charset='utf-8')
34-
attachment.add_header('Content-Disposition', 'attachment',
35-
filename=os.path.basename(attachment_file))
38+
with open(attachment_file, "rb") as attachment_fp:
39+
attachment = MIMEText(attachment_fp.read(), _charset="utf-8")
40+
attachment.add_header(
41+
"Content-Disposition",
42+
"attachment",
43+
filename=os.path.basename(attachment_file),
44+
)
3645
attachments.append(attachment)
3746
return attachments
3847

3948

40-
def do_email(mailserver, port, user, domain, password, recipients, message,
41-
subject, attachments=None):
49+
def do_email(
50+
mailserver: str,
51+
port: int,
52+
user: str,
53+
domain: str,
54+
password: str,
55+
recipients: list[str],
56+
message: str,
57+
subject: str,
58+
attachments: Optional[os.PathLike] = None,
59+
):
4260
smtp_args = []
4361
if mailserver:
4462
smtp_args.append(mailserver)
@@ -50,88 +68,101 @@ def do_email(mailserver, port, user, domain, password, recipients, message,
5068

5169
server = smtplib.SMTP(*smtp_args, timeout=10)
5270
try:
53-
#server.set_debuglevel(1)
71+
if DEBUG:
72+
server.set_debuglevel(1)
5473
server.ehlo()
55-
if server.has_extn('STARTTLS'):
74+
if server.has_extn("STARTTLS"):
5675
server.starttls()
5776

58-
sender = '@'.join([user, domain]).encode('utf-8')
77+
sender = "@".join([user, domain]).encode("utf-8")
5978

6079
if attachments:
6180
msg = MIMEMultipart()
6281
msg.preamble = message
6382
for attachment in attachments:
6483
msg.attach(attachment)
6584
else:
66-
msg = MIMEText(message, _charset='utf-8')
67-
msg['From'] = sender
68-
msg['To'] = ', '.join(recipients)
69-
msg['Date'] = formatdate()
70-
msg['Subject'] = subject
85+
msg = MIMEText(message, _charset="utf-8")
86+
msg["From"] = sender
87+
msg["To"] = ", ".join(recipients)
88+
msg["Date"] = formatdate()
89+
msg["Subject"] = subject
7190
msg = msg.as_string()
7291

7392
try:
7493
if password:
7594
server.login(user, password)
76-
except Exception as e:
77-
print('Error logging into server: %r' % (repr(e)))
78-
#time.sleep(10)
95+
except Exception:
96+
logging.exception("Error logging into server")
97+
# time.sleep(10)
7998
res = server.sendmail(sender, recipients, msg)
80-
#if res:
81-
# print('Error sending mail: %r' % (repr(res)))
82-
#else:
83-
# print('Email sent!\n%s' % (msg, ))
99+
if DEBUG:
100+
if res:
101+
print(f"Error sending mail: {res!r}")
102+
else:
103+
print(f"Email sent!\n{msg}")
84104
finally:
85105
server.quit()
86106

87107

88108
def main():
89-
import optparse
90-
91-
parser = optparse.OptionParser()
92-
parser.add_option('-d', default='.'.join(socket.getfqdn().split('.')[1:]),
93-
dest='sender_domain',
94-
help=('domain name to use for sender email '
95-
'(default: %default)'),
96-
)
97-
parser.add_option('-m', default='localhost',
98-
dest='mailserver',
99-
help='mailserver to use for relaying email',
100-
)
101-
parser.add_option('-p', default=socket.getservbyname('smtp'),
102-
dest='port',
103-
type=int,
104-
help='port to connect to SMTP on (default: %default)',
105-
)
106-
parser.add_option('-s',
107-
dest='subject',
108-
help='subject line in email to send',
109-
)
110-
parser.add_option('-u', default=os.getenv('USER'),
111-
dest='sender_user',
112-
help=('username to use when sending mail '
113-
'(default: %default)'),
114-
)
115-
116-
opts, recipients = parser.parse_args()
117-
if not len(recipients):
118-
parser.exit('you must supply at least one recipient')
119-
120-
password = os.getenv('PASSWORD') or getpass.getpass()
121-
password = password.strip().encode('utf-8')
109+
parser = argparse.ArgumentParser()
110+
parser.add_argument(
111+
"-d",
112+
default=".".join(socket.getfqdn().split(".")[1:]),
113+
dest="sender_domain",
114+
help=("domain name to use for sender email " "(default: %default)"),
115+
)
116+
parser.add_argument(
117+
"-m",
118+
default="localhost",
119+
dest="mailserver",
120+
help="mailserver to use for relaying email",
121+
)
122+
parser.add_argument(
123+
"-p",
124+
default=socket.getservbyname("smtp"),
125+
dest="port",
126+
type=int,
127+
help="port to connect to SMTP on (default: %default)",
128+
)
129+
parser.add_argument(
130+
"-s",
131+
dest="subject",
132+
help="subject line in email to send",
133+
)
134+
parser.add_argument(
135+
"-u",
136+
default=os.getenv("USER"),
137+
dest="sender_user",
138+
help=("username to use when sending mail " "(default: %default)"),
139+
)
140+
parser.add_argument("recipients", nargs="+")
141+
142+
args = parser.parse_args()
143+
144+
password = os.getenv("PASSWORD") or getpass.getpass()
145+
password = password.strip().encode("utf-8")
122146

123147
rlist = [sys.stdin]
124148

125149
while True:
126150
ready = select.select(rlist, [], [])
127151
msg = ready[0][0].read()
128152
if msg:
129-
do_email(opts.mailserver, opts.port, opts.sender_user,
130-
opts.sender_domain, password, recipients, msg,
131-
opts.subject)
153+
do_email(
154+
args.mailserver,
155+
args.port,
156+
args.sender_user,
157+
args.sender_domain,
158+
password,
159+
args.recipients,
160+
msg,
161+
args.subject,
162+
)
132163
else:
133164
time.sleep(1)
134165

135-
if __name__ == '__main__':
136-
main()
137166

167+
if __name__ == "__main__":
168+
main()

0 commit comments

Comments
 (0)