Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 992cf1d

Browse files
Issue #18972: Modernize email examples and use the argparse module in them.
1 parent ce28e2c commit 992cf1d

3 files changed

Lines changed: 56 additions & 80 deletions

File tree

Doc/includes/email-dir.py

Lines changed: 36 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
# For guessing MIME type based on file name extension
99
import mimetypes
1010

11-
from optparse import OptionParser
11+
from argparse import ArgumentParser
1212

1313
from email import encoders
1414
from email.message import Message
@@ -22,44 +22,36 @@
2222

2323

2424
def main():
25-
parser = OptionParser(usage="""\
25+
parser = ArgumentParser(description="""\
2626
Send the contents of a directory as a MIME message.
27-
28-
Usage: %prog [options]
29-
3027
Unless the -o option is given, the email is sent by forwarding to your local
3128
SMTP server, which then does the normal delivery process. Your local machine
3229
must be running an SMTP server.
3330
""")
34-
parser.add_option('-d', '--directory',
35-
type='string', action='store',
36-
help="""Mail the contents of the specified directory,
37-
otherwise use the current directory. Only the regular
38-
files in the directory are sent, and we don't recurse to
39-
subdirectories.""")
40-
parser.add_option('-o', '--output',
41-
type='string', action='store', metavar='FILE',
42-
help="""Print the composed message to FILE instead of
43-
sending the message to the SMTP server.""")
44-
parser.add_option('-s', '--sender',
45-
type='string', action='store', metavar='SENDER',
46-
help='The value of the From: header (required)')
47-
parser.add_option('-r', '--recipient',
48-
type='string', action='append', metavar='RECIPIENT',
49-
default=[], dest='recipients',
50-
help='A To: header value (at least one required)')
51-
opts, args = parser.parse_args()
52-
if not opts.sender or not opts.recipients:
53-
parser.print_help()
54-
sys.exit(1)
55-
directory = opts.directory
31+
parser.add_argument('-d', '--directory',
32+
help="""Mail the contents of the specified directory,
33+
otherwise use the current directory. Only the regular
34+
files in the directory are sent, and we don't recurse to
35+
subdirectories.""")
36+
parser.add_argument('-o', '--output',
37+
metavar='FILE',
38+
help="""Print the composed message to FILE instead of
39+
sending the message to the SMTP server.""")
40+
parser.add_argument('-s', '--sender', required=True,
41+
help='The value of the From: header (required)')
42+
parser.add_argument('-r', '--recipient', required=True,
43+
action='append', metavar='RECIPIENT',
44+
default=[], dest='recipients',
45+
help='A To: header value (at least one required)')
46+
args = parser.parse_args()
47+
directory = args.directory
5648
if not directory:
5749
directory = '.'
5850
# Create the enclosing (outer) message
5951
outer = MIMEMultipart()
6052
outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
61-
outer['To'] = COMMASPACE.join(opts.recipients)
62-
outer['From'] = opts.sender
53+
outer['To'] = COMMASPACE.join(args.recipients)
54+
outer['From'] = args.sender
6355
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
6456

6557
for filename in os.listdir(directory):
@@ -76,38 +68,32 @@ def main():
7668
ctype = 'application/octet-stream'
7769
maintype, subtype = ctype.split('/', 1)
7870
if maintype == 'text':
79-
fp = open(path)
80-
# Note: we should handle calculating the charset
81-
msg = MIMEText(fp.read(), _subtype=subtype)
82-
fp.close()
71+
with open(path) as fp:
72+
# Note: we should handle calculating the charset
73+
msg = MIMEText(fp.read(), _subtype=subtype)
8374
elif maintype == 'image':
84-
fp = open(path, 'rb')
85-
msg = MIMEImage(fp.read(), _subtype=subtype)
86-
fp.close()
75+
with open(path, 'rb') as fp:
76+
msg = MIMEImage(fp.read(), _subtype=subtype)
8777
elif maintype == 'audio':
88-
fp = open(path, 'rb')
89-
msg = MIMEAudio(fp.read(), _subtype=subtype)
90-
fp.close()
78+
with open(path, 'rb') as fp:
79+
msg = MIMEAudio(fp.read(), _subtype=subtype)
9180
else:
92-
fp = open(path, 'rb')
93-
msg = MIMEBase(maintype, subtype)
94-
msg.set_payload(fp.read())
95-
fp.close()
81+
with open(path, 'rb') as fp:
82+
msg = MIMEBase(maintype, subtype)
83+
msg.set_payload(fp.read())
9684
# Encode the payload using Base64
9785
encoders.encode_base64(msg)
9886
# Set the filename parameter
9987
msg.add_header('Content-Disposition', 'attachment', filename=filename)
10088
outer.attach(msg)
10189
# Now send or store the message
10290
composed = outer.as_string()
103-
if opts.output:
104-
fp = open(opts.output, 'w')
105-
fp.write(composed)
106-
fp.close()
91+
if args.output:
92+
with open(args.output, 'w') as fp:
93+
fp.write(composed)
10794
else:
108-
s = smtplib.SMTP('localhost')
109-
s.sendmail(opts.sender, opts.recipients, composed)
110-
s.quit()
95+
with smtplib.SMTP('localhost') as s:
96+
s.sendmail(args.sender, args.recipients, composed)
11197

11298

11399
if __name__ == '__main__':

Doc/includes/email-unpack.py

Lines changed: 15 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -8,41 +8,27 @@
88
import errno
99
import mimetypes
1010

11-
from optparse import OptionParser
11+
from argparse import ArgumentParser
1212

1313

1414
def main():
15-
parser = OptionParser(usage="""\
15+
parser = ArgumentParser(description="""\
1616
Unpack a MIME message into a directory of files.
17-
18-
Usage: %prog [options] msgfile
1917
""")
20-
parser.add_option('-d', '--directory',
21-
type='string', action='store',
22-
help="""Unpack the MIME message into the named
23-
directory, which will be created if it doesn't already
24-
exist.""")
25-
opts, args = parser.parse_args()
26-
if not opts.directory:
27-
parser.print_help()
28-
sys.exit(1)
18+
parser.add_argument('-d', '--directory', required=True,
19+
help="""Unpack the MIME message into the named
20+
directory, which will be created if it doesn't already
21+
exist.""")
22+
parser.add_argument('msgfile')
23+
args = parser.parse_args()
2924

30-
try:
31-
msgfile = args[0]
32-
except IndexError:
33-
parser.print_help()
34-
sys.exit(1)
25+
with open(args.msgfile) as fp:
26+
msg = email.message_from_file(fp)
3527

3628
try:
37-
os.mkdir(opts.directory)
38-
except OSError as e:
39-
# Ignore directory exists error
40-
if e.errno != errno.EEXIST:
41-
raise
42-
43-
fp = open(msgfile)
44-
msg = email.message_from_file(fp)
45-
fp.close()
29+
os.mkdir(args.directory)
30+
except FileExistsError:
31+
pass
4632

4733
counter = 1
4834
for part in msg.walk():
@@ -59,9 +45,8 @@ def main():
5945
ext = '.bin'
6046
filename = 'part-%03d%s' % (counter, ext)
6147
counter += 1
62-
fp = open(os.path.join(opts.directory, filename), 'wb')
63-
fp.write(part.get_payload(decode=True))
64-
fp.close()
48+
with open(os.path.join(args.directory, filename), 'wb') as fp:
49+
fp.write(part.get_payload(decode=True))
6550

6651

6752
if __name__ == '__main__':

Misc/NEWS

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ Library
6060
- Issue #4366: Fix building extensions on all platforms when --enable-shared
6161
is used.
6262

63+
Documentation
64+
-------------
65+
66+
- Issue #18972: Modernize email examples and use the argparse module in them.
67+
6368
Build
6469
-----
6570

0 commit comments

Comments
 (0)